### Lust CLI Help and REPL Source: https://lust-lang.dev/docs/quick-start Demonstrates how to access the help menu for the Lust CLI and how to start the Read-Eval-Print Loop (REPL) for interactive code exploration. ```shell lust --help lust repl ``` -------------------------------- ### Download and Extract Lust CLI (Linux x86_64) Source: https://lust-lang.dev/docs/quick-start Downloads the Lust CLI binary archive for Linux x86_64 using curl and then extracts the contents using tar. This is the first step in installing the CLI. ```shell curl -OL https://lust-lang.dev/downloads/lust-linux-x86_64.tar.gz tar -xf lust-linux-x86_64.tar.gz ``` -------------------------------- ### Run Lust Program Source: https://lust-lang.dev/docs/quick-start Executes a Lust program file using the installed Lust CLI. The CLI automatically loads, type-checks, and runs the specified script. ```shell lust examples/basic/01_hello.lust ``` -------------------------------- ### Add Lust Binary to PATH Source: https://lust-lang.dev/docs/quick-start Sets the Lust binary directory to the system's PATH environment variable, allowing the 'lust' command to be executed from any directory. This assumes the binary was extracted into a 'lust/bin' subdirectory. ```shell export PATH="$PWD/lust/bin:$PATH" ``` -------------------------------- ### Organize Code with Modules in Lust Source: https://lust-lang.dev/docs/print Shows how to structure code into modules using `pub` for exports and `use` for imports. This example demonstrates aliasing modules, importing specific items, and handling nested modules for better code organization and reusability. ```lust -- lib/math.lust println("[lib.math] init") pub struct Point x: int y: int end pub function add(a: int, b: int): int return a + b end ``` ```lust -- lib/math/vector.lust println("[lib.math.vector] init") pub struct IntVector x: int y: int end pub function make(x: int, y: int): IntVector return IntVector { x = x, y = y } end pub function length_squared(vec: IntVector): int return (vec.x * vec.x) + (vec.y * vec.y) end ``` ```lust -- main.lust use lib.math as math use lib.math.{Point, vector} use lib.math.{add, vector.length_squared, vector.make as make_vector} println("[main] grouped imports showcase") local p: Point = Point { x = 10, y = 20 } println("Point.y = " .. tostring(p.y)) println("math.add via alias = " .. tostring(math.add(1, 2))) println("add via import = " .. tostring(add(3, 4))) local velocity: vector.IntVector = make_vector(3, 4) println("length^2 = " .. tostring(length_squared(velocity))) ``` -------------------------------- ### Disassemble Lust Program to Bytecode Source: https://lust-lang.dev/docs/quick-start Compiles and disassembles a Lust program to inspect its bytecode. This is useful for understanding the intermediate representation of the code. ```shell lust --disassemble examples/basic/05_enums.lust ``` -------------------------------- ### Create a Lust Task Source: https://lust-lang.dev/docs/language-tour/tasks Demonstrates creating a new task using `task.create`. The `task.create` function accepts a closure and returns a `Task` handle. The closure does not execute immediately; it starts on the first `task.resume` call. ```lust local ticker: Task = task.create(function(): string for step = 1, 3 do task.yield("tick " .. tostring(step)) end return "done" end) ``` -------------------------------- ### Lust Numeric and String Manipulation Source: https://lust-lang.dev/docs/language-tour/data-control Presents examples of Lust's built-in helper functions for numeric and string types. Numeric helpers include floor, clamp, etc., while string helpers cover starts_with, replace, and split, often returning Option types for robust error handling. ```lust local angle: float = 7.5 println("floor = " .. tostring(angle:floor())) println("clamp = " .. tostring(angle:clamp(0.0, 5.0))) local phrase = "Hello, World!" println(phrase:starts_with("Hello")) println(phrase:replace("World", "Lust")) local parts = phrase:split(", ") for part in parts do println("part = " .. part) end ``` -------------------------------- ### Verify Lust CLI Integrity with SHA256 Source: https://lust-lang.dev/docs/quick-start Downloads the SHA256 checksum file for the Lust CLI binary and then uses the 'shasum' command to verify the integrity of the downloaded archive. This ensures the downloaded file has not been corrupted or tampered with. ```shell curl -OL https://lust-lang.dev/downloads/lust-linux-x86_64.tar.gz.sha256 shasum -a 256 -c lust-linux-x86_64.tar.gz.sha256 ``` -------------------------------- ### Option and Result Enum Usage in Lust Source: https://lust-lang.dev/docs/language-tour/type-system Provides examples of using the `Option` and `Result` enums from the standard library. It shows how to check for `Some` values in `Option` and handle `Err` cases in `Result` using pattern matching and convenience methods. ```lust function find_even(value: int): Option if value % 2 == 0 then return Option.Some(value) end return Option.None end function divide(a: int, b: int): Result if b == 0 then return Result.Err("division by zero") end return Result.Ok(a / b) end if find_even(42) is Some(n) then println("even: " .. tostring(n)) end local result = divide(10, 0) if result:is_err() then println(result:unwrap_err()) end ``` -------------------------------- ### Get Information about a Lust Task Source: https://lust-lang.dev/docs/language-tour/tasks Illustrates retrieving detailed information about a task using `task.info`. This includes the task's current state, its last result if completed, or any error if it failed. ```lust local info: TaskInfo = task.info(ticker) println("state = " .. tostring(info.state)) println("result = " .. tostring(info.last_result:unwrap_or("None"))) println("error = " .. info.error:unwrap_or("None")) ``` -------------------------------- ### Multiple Return Values in Lust Functions Source: https://lust-lang.dev/docs/language-tour/type-system Illustrates how Lust functions can return multiple values, treated as tuples. The example shows a function returning a string, a boolean, and an integer, and how these can be destructured into separate variables. ```lust function checkpoint(label: string, value: int): (string, bool, int) local positive = value > 0 return label, positive, value end local tag: string, ok: bool, score: int = checkpoint("quests", 5) println(tag .. " -> " .. tostring(score) .. " (positive=" .. tostring(ok) .. ")") ``` -------------------------------- ### Handling `unknown` Types with `is` and `and` Source: https://lust-lang.dev/docs/language-tour/type-system Shows how to safely work with `unknown` types in Lust, which are common when dealing with dynamic structures or foreign data. The example demonstrates narrowing an `unknown` value to a specific type (e.g., `int`) using `is` and `and` before accessing its properties. ```lust local tags: Map = { ["io"] = "123ABC", ["os"] = "second", ["age"] = 56 } if tags:get("age") is Some(val) and val is int then println("Value is int: " .. val) else println("Value is string") end ``` -------------------------------- ### Handle Fallible Operations with Result in Lust Source: https://lust-lang.dev/docs/print Illustrates the 'divide' function which returns a 'Result', indicating success with an integer quotient or failure with an error message. The example shows how to check for errors and unwrap the error value. ```lust __ function divide(a: int, b: int): Result if b == 0 then return Result.Err("division by zero") end return Result.Ok(a / b) end ``` ```lust __ local result = divide(10, 0) if result:is_err() then println(result:unwrap_err()) end ``` -------------------------------- ### Round-Robin Task Execution in Lust Source: https://lust-lang.dev/docs/language-tour/tasks A helper function `step_task` is defined to drive tasks round-robin. It checks task status, resumes them, and reports their state, result, or error. This example demonstrates orchestrating multiple tasks concurrently. ```lust function step_task(label: string, handle: Task): bool local status = task.status(handle) if status is Completed or status is Failed or status is Stopped then local info = task.info(handle) println(label .. " state = " .. tostring(info.state)) println(label .. " result = " .. tostring(info.last_result:unwrap_or("None"))) println(label .. " error = " .. tostring(info.error:unwrap_or("None"))) return true end local frame = task.resume(handle) println(label .. " yield = " .. tostring(frame.last_yield:unwrap_or("None"))) return false end local task_a = task.create(function() for n = 1, 2 do task.yield("A-" .. tostring(n)) end return "A-done" end) local task_b = task.create(function() task.yield("B-start") return "B-done" end) local task_c = task.create(function() task.yield("C") error("boom") -- demonstrates failure reporting end) local active: Array = [task_a, task_b, task_c] while active:len() > 0 do local next_round: Array = [] for handle in active do if not step_task("task", handle) then next_round:push(handle) end end active = next_round end ``` -------------------------------- ### Run and Disassemble Lust Scripts with CLI Source: https://lust-lang.dev/docs/print The Lust CLI binary 'lust' supports running scripts directly and disassembling them to view bytecode. Use '--help' or '-h' for usage information and '--version' or '-v' for the release version. ```bash lust script.lust lust --disassemble script.lust lust --help lust -h lust --version lust -v ``` -------------------------------- ### Cooperative Tasks and Scheduling in Lust Source: https://lust-lang.dev/docs/language-tour/overview Demonstrates the use of Lust's cooperative task scheduler. It shows how to create a task, yield control, and resume the task, observing its status and return values. ```lust local ticker: Task = task.create(function(): string for step = 1, 3 do task.yield("tick " .. tostring(step)) end return "done" end) while task.status(ticker) == TaskStatus.Running do local frame = task.resume(ticker) println(frame.last_yield:unwrap_or("idle")) end ``` -------------------------------- ### Basic Output and Variable Declaration in Lust Source: https://lust-lang.dev/docs/language-tour/overview Demonstrates basic printing and variable declaration with type annotations in Lust. It shows how top-level statements run immediately and how string concatenation works. ```lust println("Hello from Lust!") local who: string = "traveler" println("A Lua-inspired language with strict typing for the " .. who) ``` -------------------------------- ### Embed Lust in C using C ABI Source: https://lust-lang.dev/docs/embedding Illustrates embedding Lust into a C application using the provided C ABI. It covers creating a builder, adding modules, compiling the program, running entry scripts, calling Lust functions with arguments, and handling results. ```c EmbeddedBuilder *builder = lust_builder_new(); lust_builder_add_module(builder, "main", module_source); lust_builder_set_entry_module(builder, "main"); EmbeddedProgram *program = lust_builder_compile(builder); if (!lust_program_run_entry(program)) { die_with_last_error("lust_program_run_entry"); } LustFfiValue args[2] = { {.tag = LUST_FFI_VALUE_INT, .int_value = 20}, {.tag = LUST_FFI_VALUE_INT, .int_value = 22}, }; LustFfiValue result = {0}; if (!lust_program_call(program, "main.add", args, 2, &result)) { die_with_last_error("lust_program_call"); } printf("20 + 22 = %lld\n", (long long)result.int_value); lust_value_dispose(&result); lust_program_free(program); ``` -------------------------------- ### Lust Task Creation Source: https://lust-lang.dev/docs/print Demonstrates how to create a new cooperative task using `task.create`. The provided closure is not executed immediately but is ready to be resumed. ```lust local ticker: Task = task.create(function(): string for step = 1, 3 do task.yield("tick " .. tostring(step)) end return "done" end) ``` -------------------------------- ### Implementing and Using Traits Source: https://lust-lang.dev/docs/language-tour/type-system Demonstrates defining traits (`Drawable`, `Printable`) with required methods and implementing them for a struct (`Circle`) in Lust. It also shows how to use trait bounds (`T: Drawable`) for static dispatch and how traits can be used with narrowing and casting. ```lust trait Drawable function draw(self) end trait Printable function print(self) end struct Circle radius: float end impl Drawable for Circle function draw(self) println("Drawing circle with radius " .. tostring(self.radius)) end end function render(shape: T) shape:draw() end ``` -------------------------------- ### Function Definition and Usage in Lust Source: https://lust-lang.dev/docs/language-tour/overview Illustrates function definition with type annotations for arguments and return values, and demonstrates multiple return values (tuples) in Lust. It also shows the familiar control flow syntax. ```lust function describe(label: string, score: int): (bool, int) local positive = score > 0 return positive, score end local ok, total = describe("quests", 42) if ok then println("quests total = " .. tostring(total)) end ``` -------------------------------- ### Basic Type Annotations and Inference in Lust Source: https://lust-lang.dev/docs/print Illustrates Lust's type system, showing how to declare variables with explicit types or rely on type inference. It also demonstrates function type annotations for arguments and return values. ```lust __ local count: int = 42 local name = "Lust" -- inferred string local active = true -- inferred bool function add(a: int, b: int): int return a + b end local total = add(count, 8) -- inferred as int ``` -------------------------------- ### Implement Cooperative Tasks in Lust Source: https://lust-lang.dev/docs/print Demonstrates creating and managing cooperative tasks using the `task` module. Tasks can yield control using `task.yield` and be resumed later with `task.resume`, allowing for concurrent execution patterns. ```lust __ local ticker: Task = task.create(function(): string for step = 1, 3 do task.yield("tick " .. tostring(step)) end return "done" end) while task.status(ticker) == TaskStatus.Running do local frame = task.resume(ticker) println(frame.last_yield:unwrap_or("idle")) end ``` -------------------------------- ### Lust Map and Option Types Source: https://lust-lang.dev/docs/language-tour/data-control Illustrates the usage of Lust's Map type, which can mimic Lua tables, and the Option type for handling potentially missing values. It shows how to access map keys, check for the presence of values, and unwrap them safely. ```lust local tags: Map = { ["io"] = "123ABC", ["os"] = "second", ["age"] = 56 } println(tags:keys():len()) if tags:get("age") is Some(val) and val is int then println("Value is int: " .. val) else println("Value is string") end local maybe_io = tags:get("io") if maybe_io:is_some() then local raw = maybe_io:unwrap() if raw is string then println(raw) end end ``` -------------------------------- ### Module System and Imports in Lust Source: https://lust-lang.dev/docs/language-tour/overview Illustrates Lust's module system, including defining public exports (`pub`), creating nested modules, and various ways to import modules and their members. It showcases aliasing and selective imports. ```lust -- lib/math.lust println("[lib.math] init") pub struct Point x: int y: int end pub function add(a: int, b: int): int return a + b end ``` ```lust -- lib/math/vector.lust println("[lib.math.vector] init") pub struct IntVector x: int y: int end pub function make(x: int, y: int): IntVector return IntVector { x = x, y = y } end pub function length_squared(vec: IntVector): int return (vec.x * vec.x) + (vec.y * vec.y) end ``` ```lust -- main.lust use lib.math as math use lib.math.{Point, vector} use lib.math.{add, vector.length_squared, vector.make as make_vector} println("[main] grouped imports showcase") local p: Point = Point { x = 10, y = 20 } println("Point.y = " .. tostring(p.y)) println("math.add via alias = " .. tostring(math.add(1, 2))) println("add via import = " .. tostring(add(3, 4))) local velocity: vector.IntVector = make_vector(3, 4) println("length^2 = " .. tostring(length_squared(velocity))) ``` -------------------------------- ### Embed Lust in Rust using EmbeddedProgram Builder Source: https://lust-lang.dev/docs/embedding Demonstrates how to compile and run Lust modules within a Rust application using the `lust_rs::EmbeddedProgram::builder`. It shows registering native Rust functions, calling Lust functions, and instantiating Lust structs. ```rust use lust_rs::{EmbeddedProgram, StructInstance}; fn main() -> lust_rs::Result<()> { let module_source = r#" struct Point x: int y: int end extern { function host_scale(int): int } pub function amplify(value: int): int return host_scale(value) * 3 end "#; let mut program = EmbeddedProgram::builder() .module("main", module_source) .entry_module("main") .compile()?; // Module-level statements run once so globals are initialized. program.run_entry_script()?; program.register_typed_native("host_scale", |value: i64| Ok(value * 10))?; let amplified: i64 = program.call_typed("main.amplify", 7_i64)?; println!("Amplify(7) -> {amplified}"); let point: StructInstance = program.struct_instance("main.Point", vec![("x", 1_i64), ("y", 2_i64)])?; println!("Point.x = {}", point.field::("x")?); Ok(()) } ``` -------------------------------- ### Lust Closures and Higher-Order Functions Source: https://lust-lang.dev/docs/language-tour/data-control Demonstrates how Lust handles closures, including anonymous functions capturing upvalues and returning lambdas to create factories or configure higher-order helpers. It showcases function nesting and variable scoping. ```lust local multiplier = 3 local scale = function(value: int): int return value * multiplier end println(scale(5)) local make_adder = function(base: int) return function(offset: int): int return base + offset end end local add10 = make_adder(10) println(add10(5)) ``` -------------------------------- ### Define and Implement Traits for Structs in Lust Source: https://lust-lang.dev/docs/print Demonstrates defining traits (Drawable, Printable) and implementing them for a struct (Circle). It also shows how to use generic functions with trait bounds for static dispatch. ```lust __ trait Drawable function draw(self) end trait Printable function print(self) end struct Circle radius: float end impl Drawable for Circle function draw(self) println("Drawing circle with radius " .. tostring(self.radius)) end end function render(shape: T) shape:draw() end ``` -------------------------------- ### Drive Tasks Round-Robin with Lust Source: https://lust-lang.dev/docs/print Demonstrates using Lust's task system to drive tasks in a round-robin fashion. It includes a helper function `step_task` to manage task status, gather diagnostics, and resume tasks. This approach allows for interleaved execution without explicit locking mechanisms. ```lust function step_task(label: string, handle: Task): bool local status = task.status(handle) if status is Completed or status is Failed or status is Stopped then local info = task.info(handle) println(label .. " state = " .. tostring(info.state)) println(label .. " result = " .. tostring(info.last_result:unwrap_or("None"))) println(label .. " error = " .. info.error:unwrap_or("None")) return true end local frame = task.resume(handle) println(label .. " yield = " .. tostring(frame.last_yield:unwrap_or("None"))) return false end local task_a = task.create(function() for n = 1, 2 do task.yield("A-" .. tostring(n)) end return "A-done" end) local task_b = task.create(function() task.yield("B-start") return "B-done" end) local task_c = task.create(function() task.yield("C") error("boom") -- demonstrates failure reporting end) local active: Array = [task_a, task_b, task_c] while active:len() > 0 do local next_round: Array = [] for handle in active do if not step_task("task", handle) then next_round:push(handle) end end active = next_round end ``` -------------------------------- ### Type Inspection and Casting with Traits in Lust Source: https://lust-lang.dev/docs/print Illustrates how to inspect values for trait implementations using `is` and cast them using `:as()`. This allows for dynamic behavior based on available traits. ```lust __ function inspect(value: unknown) if value is Drawable then value:draw() return end local printable = value:as() if printable:is_some() then printable:unwrap():print() end end ``` -------------------------------- ### Lust Loops: While and For Source: https://lust-lang.dev/docs/print Demonstrates the usage of 'while' and numeric 'for' loops in Lust. 'while' loops execute as long as a condition is true, while numeric 'for' loops iterate over a specified range with an optional step. Supports 'break' and 'continue'. ```lust println("=== while ===") local i = 1 while i <= 3 do println(i) i = i + 1 end println("=== numeric for ===") for step = 0, 10, 2 do println(step) end ``` -------------------------------- ### Primitive Type Helper Methods Source: https://lust-lang.dev/docs/language-tour/type-system Showcases the rich set of helper methods available for primitive types in Lust, such as numeric methods (`floor`, `clamp`) and string methods (`find`, `to_upper`). These helpers integrate seamlessly with Option/Result flows and higher-order functions. ```lust local x: float = 3.75 println(x:floor()) println(x:clamp(0.0, 2.0)) local greeting = "Hello, Lust!" println(greeting:find("Lust"):unwrap_or(-1)) println(greeting:to_upper()) ``` -------------------------------- ### Using Option Type for Optional Values in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Demonstrates the `Option` type in Lust for representing values that may or may not be present. It shows how to check for `Some` or `None` and unwrap values with a default. ```lust function find_even(n: int): Option if n % 2 == 0 then return Option.Some(n) end return Option.None end local maybe_even = find_even(total) println("even? " .. tostring(maybe_even:is_some())) println("value = " .. tostring(maybe_even:unwrap_or(-1))) ``` -------------------------------- ### Narrowing to Traits and Casting Source: https://lust-lang.dev/docs/language-tour/type-system Illustrates how to narrow an `unknown` value to a specific trait (`Drawable`) in Lust, making trait methods available. It also shows using the `:as()` method to attempt casting to a trait and handling the `Option` result. ```lust function inspect(value: unknown) if value is Drawable then value:draw() return end local printable = value:as() if printable:is_some() then printable:unwrap():print() end end ``` -------------------------------- ### Embed Lust Runtime in Rust using Builder API Source: https://lust-lang.dev/docs/print Shows how to embed the Lust runtime within a Rust application using the `lust_rs` crate. It demonstrates compiling Lust modules, registering native Rust functions to be called from Lust, executing Lust functions, and creating Lust struct instances from Rust. ```rust use lust_rs::{EmbeddedProgram, StructInstance}; fn main() -> lust_rs::Result<()> { let module_source = r#" struct Point x: int y: int end extern { function host_scale(int): int } pub function amplify(value: int): int return host_scale(value) * 3 end "#; let mut program = EmbeddedProgram::builder() .module("main", module_source) .entry_module("main") .compile()?; // Module-level statements run once so globals are initialized. program.run_entry_script()?; program.register_typed_native("host_scale", |value: i64| Ok(value * 10))?; let amplified: i64 = program.call_typed("main.amplify", 7_i64)?; println!("Amplify(7) -> {amplified}"); let point: StructInstance = program.struct_instance("main.Point", vec![("x", 1_i64), ("y", 2_i64)])?; println!("Point.x = {}", point.field::("x")?); Ok(()) } ``` -------------------------------- ### Define and Use Structs with Methods in Lust Source: https://lust-lang.dev/docs/print Demonstrates defining a 'Node' struct with name, parent, and children fields, and implementing methods like 'new' and 'attach_child'. 'ref' fields are used for weak parent references to prevent ownership cycles. ```lust __ struct Node name: string, parent: ref Node, children: Array end impl Node function new(name: string): Node return Node { name = name, parent = Option.None, children = [] } end function attach_child(self, child: Node): Node child.parent = self -- assigning to a ref sets a weak link self.children:push(child) return child end end ``` -------------------------------- ### Function Return Tuples and Destructuring in Lust Source: https://lust-lang.dev/docs/print Demonstrates how to define functions that return multiple values as tuples and how to destructure these tuples upon function call. It also shows destructuring within conditional statements. ```lust __ function split_stats(label: string, score: int): (string, bool, int) local is_positive = score > 0 return label, is_positive, score end local title, positive, total = split_stats("quests", 12) println(title .. ": total=" .. tostring(total) .. " (positive=" .. tostring(positive) .. ")") ``` ```lust __ if fetch_user() is Ok(user) and user.profile is Some(profile) then println("user name = " .. profile.name) end ``` -------------------------------- ### Typed Collections in Lust Source: https://lust-lang.dev/docs/language-tour/overview Demonstrates the use of built-in typed collections like `Array` and `Map` in Lust. It shows how to add elements to an array and access map properties, along with common collection methods. ```lust local scores: Array = [10, 20, 30] local tags: Map = { ["core"] = 1, ["jit"] = 2 } scores:push(40) println(tags:keys():len()) ``` -------------------------------- ### Define and Call Functions Returning Tuples in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Illustrates defining a function that returns multiple values (a tuple) and how to call it, destructuring the returned values. It highlights Lust's type annotations for function return types. ```lust function split_stats(label: string, score: int): (string, bool, int) local is_positive = score > 0 return label, is_positive, score end local title, positive, total = split_stats("quests", 12) println(title .. ": total=" .. tostring(total) .. " (positive=" .. tostring(positive) .. ")") ``` -------------------------------- ### Lust Task Resumption and Status Source: https://lust-lang.dev/docs/print Explains how to resume a task using `task.resume` and check its status using `task.status`. This allows for step-by-step execution and monitoring of task lifecycles. ```lust while true do local status = task.status(ticker) if status is Completed or status is Failed or status is Stopped then break end local frame = task.resume(ticker) println("yielded " .. tostring(frame.last_yield:unwrap_or("idle"))) end ``` -------------------------------- ### Short-Circuit Evaluation for Conditional Expressions in Lust Source: https://lust-lang.dev/docs/print Illustrates Lust's use of short-circuit evaluation for conditional expressions, similar to Lua's `and`/`or` behavior, to provide concise ways to handle default values or conditional execution. ```lust __ local age = 28 -- age is an 'int' local status = age >= 30 and "old" or "young" -- status is inferred as a 'string' type println(status) -- Result: "young" function computation(): bool println("Some computation") return true end local check = false -- check is a 'bool' local result = check and computation() or "fallback" -- result is inferred as a 'bool | string' type println(result) -- Result: "fallback" ``` -------------------------------- ### Basic Loop Constructs in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Covers Lust's `while` and numeric `for` loop constructs, which function similarly to Lua. It also mentions `break` and `continue` for loop control. ```lust println("=== while ===") local i = 1 while i <= 3 do println(i) i = i + 1 end println("=== numeric for ===") for step = 0, 10, 2 do println(step) end ``` -------------------------------- ### Data Structures: Structs and Enums in Lust Source: https://lust-lang.dev/docs/language-tour/overview Shows the definition of custom data structures like structs and enums in Lust. It also demonstrates implementing methods for structs using the `impl` block and how to call these methods. ```lust struct Point x: int y: int end enum Status Pending, Running, Complete(int) end impl Point function translate(self, dx: int, dy: int): Point return Point { x = self.x + dx, y = self.y + dy } end end ``` -------------------------------- ### Lust Collection Methods: Map, Filter, Reduce Source: https://lust-lang.dev/docs/print Illustrates the use of functional programming methods on arrays: 'map' for transformation, 'filter' for selection, and 'reduce' for aggregation. These methods operate on collections and can capture external variables. ```lust local numbers: Array = [1, 2, 3, 4, 5] local doubled = numbers:map(function(n) return n * 2 end) local evens = doubled:filter(function(n) return n % 2 == 0 end) local total: int = evens:reduce(0, function(acc, n) return acc + n end) println("doubled = " .. tostring(doubled)) println("even sum = " .. tostring(total)) ``` -------------------------------- ### Using Built-in Methods for Primitive Types in Lust Source: https://lust-lang.dev/docs/print Shows the usage of built-in helper methods for primitive types like float and string. These include mathematical operations, string manipulation, and case conversion. ```lust __ local x: float = 3.75 println(x:floor()) println(x:clamp(0.0, 2.0)) local greeting = "Hello, Lust!" println(greeting:find("Lust"):unwrap_or(-1)) println(greeting:to_upper()) ``` -------------------------------- ### Short-Circuit Evaluation for Conditionals in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Explains Lust's use of short-circuit evaluation (`and`, `or`) for conditional logic, similar to Lua, to avoid unnecessary computations and provide fallbacks. ```lust local age = 28 -- age is an 'int' local status = age >= 30 and "old" or "young" -- status is inferred as a 'string' type println(status) -- Result: "young" function computation(): bool println("Some computation") return true end local check = false -- check is a 'bool' local result = check and computation() or "fallback" -- result is inferred as a 'bool | string' type println(result) -- Result: "fallback" ``` -------------------------------- ### Iterating Over Collections in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Explains how to iterate directly over arrays and maps in Lust using `for-in` loops. It shows iterating over array elements and map key-value pairs. ```lust local fruits: Array = ["apple", "banana", "cherry"] for fruit in fruits do println(fruit) end local counts: Map = { apple = 3, banana = 5 } for name, amount in counts:pairs() do println(name .. ": " .. tostring(amount)) end ``` -------------------------------- ### Lust Container Iteration: For-In Source: https://lust-lang.dev/docs/print Shows how to iterate directly over containers like Arrays and Maps using the 'for-in' loop. This provides a concise way to access elements within collections. ```lust local fruits: Array = ["apple", "banana", "cherry"] for fruit in fruits do println(fruit) end local counts: Map = { apple = 3, banana = 5 } for name, amount in counts:pairs() do println(name .. ": " .. tostring(amount)) end ``` -------------------------------- ### Lust Task Information Source: https://lust-lang.dev/docs/print Shows how to retrieve detailed information about a task, including its current state, last result, and any errors encountered, using `task.info`. ```lust local info: TaskInfo = task.info(ticker) println("state = " .. tostring(info.state)) println("result = " .. tostring(info.last_result:unwrap_or("None"))) println("error = " .. info.error:unwrap_or("None")) ``` -------------------------------- ### Struct Definition and Methods in Lust Source: https://lust-lang.dev/docs/language-tour/type-system Defines a `Node` struct with string, reference, and array fields. It also shows how to implement methods for the struct using an `impl` block, including a constructor and a method to attach child nodes. ```lust struct Node name: string, parent: ref Node, children: Array end impl Node function new(name: string): Node return Node { name = name, parent = Option.None, children = [] } end function attach_child(self, child: Node): Node child.parent = self -- assigning to a ref sets a weak link self.children:push(child) return child end end ``` -------------------------------- ### Define Structs, Enums, and Methods in Lust Source: https://lust-lang.dev/docs/print Demonstrates defining custom data structures like structs and enums, and attaching methods to types using `impl` blocks. Structs model fixed-shape data, enums capture variants, and `impl` blocks allow methods to be called on type instances. ```lust __ struct Point x: int y: int end enum Status Pending, Running, Complete(int) end impl Point function translate(self, dx: int, dy: int): Point return Point { x = self.x + dx, y = self.y + dy } end end ``` -------------------------------- ### Variable Declarations and Function Definition in Lust Source: https://lust-lang.dev/docs/language-tour/type-system Demonstrates basic variable declarations with explicit and inferred types, and defines a simple function with type annotations. Bindings are local and mutable by default. Type annotations can be omitted when inferable but are recommended for clarity. ```lust local count: int = 42 local name = "Lust" -- inferred string local active = true -- inferred bool function add(a: int, b: int): int return a + b end local total = add(count, 8) -- inferred as int ``` -------------------------------- ### Handling Results with Ok and Err in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Shows how to use the `Result` type in Lust for error handling. It demonstrates checking if a result is `Ok` or `Err` and extracting the contained value or error message. ```lust function load_score(user_id: string): Result if user_id:is_empty() then return Result.Err("missing user id") end return Result.Ok(4200) end local outcome = load_score("player-1") if outcome is Ok(score) then println("score = " .. tostring(score)) elseif outcome is Err(message) then println("cannot load score: " .. message) end ``` -------------------------------- ### Resume and Check Status of a Lust Task Source: https://lust-lang.dev/docs/language-tour/tasks Shows how to resume a task and check its status. `task.status` returns a `TaskStatus` enum, and `task.resume` advances the task to the next yield or return point, returning a record with `last_yield`. ```lust while true do local status = task.status(ticker) if status is Completed or status is Failed or status is Stopped then break end local frame = task.resume(ticker) println("yielded " .. tostring(frame.last_yield:unwrap_or("idle"))) end ``` -------------------------------- ### Array Transformation with Map, Filter, Reduce in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Demonstrates Lust's functional array methods: `map` for transforming elements, `filter` for selecting elements, and `reduce` for accumulating a result. It shows how closures can capture external variables. ```lust local numbers: Array = [1, 2, 3, 4, 5] local doubled = numbers:map(function(n) return n * 2 end) local evens = doubled:filter(function(n) return n % 2 == 0 end) local total: int = evens:reduce(0, function(acc, n) return acc + n end) println("doubled = " .. tostring(doubled)) println("even sum = " .. tostring(total)) ``` -------------------------------- ### Linear Destructuring with `is` and `and` Source: https://lust-lang.dev/docs/language-tour/type-system Illustrates how to use the `is` operator in conjunction with `and` for linear destructuring in Lust. When the left side of the `and` succeeds, any variables it introduces become visible to the right side, enabling safe access to nested data. ```lust if task_state is Ok(data) and data.user is Some(user) and user.is_admin then println("admin: " .. user.name) end ``` -------------------------------- ### Conditional Logic with Type Narrowing in Lust Source: https://lust-lang.dev/docs/language-tour/data-control Shows how Lust's `if` statements can perform type checking and narrowing on union types. It demonstrates chaining conditions with `and` for sequential checks and variable introduction. ```lust if fetch_user() is Ok(user) and user.profile is Some(profile) then println("user name = " .. profile.name) end ``` -------------------------------- ### Handle Optional Values with Option in Lust Source: https://lust-lang.dev/docs/print Shows the 'find_even' function which returns an 'Option', either 'Some(value)' if the input is even or 'None' otherwise. It also demonstrates how to use the 'is' operator to safely unwrap optional values. ```lust __ function find_even(value: int): Option if value % 2 == 0 then return Option.Some(value) end return Option.None end ``` ```lust __ if find_even(42) is Some(n) then println("even: " .. tostring(n)) end ``` -------------------------------- ### Create Generic Functions with Trait Bounds in Lust Source: https://lust-lang.dev/docs/print Demonstrates a generic function 'sum' that accepts an array of any type 'T' as long as 'T' implements the 'ToString' trait. It uses the 'reduce' collection helper to concatenate the string representations of the items. ```lust __ function sum(items: Array): string return items:reduce("", function(acc, value) if acc:is_empty() then return value:to_string() end return acc .. ", " .. value:to_string() end) end local numbers: Array = [1, 2, 3] println(sum(numbers)) local directory: Map = { ["alpha"] = 1, ["beta"] = 2 } println(directory:get("alpha"):unwrap_or(-1)) ```