### YueScript Installation: LuaRocks, Shared Library, and Binary Tool Builds Source: https://yuescript.org/doc/index Provides various shell commands for installing YueScript. This includes using LuaRocks for module installation, building a shared library (`yue.so`), and compiling the binary tool with options to disable macros or built-in Lua. ```Shell luarocks install yuescript ``` ```Shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` ```Shell make install ``` ```Shell make install NO_MACRO=true ``` ```Shell make install NO_LUA=true ``` -------------------------------- ### YueScript Command Line Tool Options and Usage Source: https://yuescript.org/doc/index This section details the command-line interface for the YueScript compiler and runtime. It lists all available options for compilation, execution, debugging, and output control, along with practical usage examples. ```APIDOC Usage: yue [options|files|directories] ... -h Print this message -e str Execute a file or raw codes -m Generate minified codes -r Rewrite output to match original line numbers -t path Specify where to place compiled files -o file Write output to file -s Use spaces in generated codes instead of tabs -p Write output to standard out -b Dump compile time (doesn't write output) -g Dump global variables used in NAME LINE COLUMN -l Write line numbers from source codes -j Disable implicit return at end of file -c Reserve comments before statement from source codes -w path Watch changes and compile every file under directory -v Print version -- Read from standard in, print to standard out (Must be first and only argument) --target=version Specify the Lua version codes the compiler will generate (version can only be 5.1, 5.2, 5.3 or 5.4) --path=path_str Append an extra Lua search path string to package.path Execute without options to enter REPL, type symbol '$' in a single line to start/stop multi-line mode Usage Examples: yue .: Recursively compile every YueScript file with extension .yue under current path. yue -t /target/path/ .: Compile and save results to a target path. yue -l .: Compile and reserve debug info. yue -m .: Compile and generate minified codes. yue -e 'print 123': Execute raw codes. yue -e main.yue: Execute a YueScript file. ``` -------------------------------- ### YueScript With Statement: Object Initialization in a Function Source: https://yuescript.org/doc/index Shows how to use the `with` statement within a function to create and configure an object based on function parameters. This example demonstrates creating a `Person` object and adding relatives dynamically. ```YueScript create_person = (name, relatives) -> with Person! .name = name \add_relative relative for relative in *relatives me = create_person "Leaf", [dad, mother, sister] ``` -------------------------------- ### Yuescript List Comprehension: Filtering with `when` Clause Source: https://yuescript.org/doc/index Illustrates how to filter elements in a list comprehension using a `when` clause. This example selects items based on their index, creating a sub-list. ```Yuescript slice = [item for i, item in ipairs items when i > 1 and i < 3] ``` -------------------------------- ### YueScript Macro for Inserting Raw Codes Source: https://yuescript.org/doc/index This example illustrates how YueScript macros can be used to insert raw code directly into the compiled output. Macros can return either a YueScript string or a configuration table specifying raw Lua code, providing a powerful mechanism for interop with Lua. ```YueScript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA funcA = -> "fail to assign to the Yue macro defined variable" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB funcB = -> "fail to assign to the Lua macro defined variable" macro lua = (code) -> { :code type: "lua" } -- the raw string leading and ending symbols are auto trimed $lua[==[ -- raw Lua codes insertion if cond then print("output") end ]==] ``` -------------------------------- ### Chaining Function Calls with Operators in YueScript Source: https://yuescript.org/doc/index Demonstrates the use of special operators `\` and `::` in YueScript for chaining function calls, providing a more fluent syntax similar to method calls in object-oriented languages. The examples include conditional execution based on a nil check. ```YueScript tb\func! if tb ~= nil tb::func! if tb != nil ``` -------------------------------- ### Implement class inheritance and method overriding in YueScript Source: https://yuescript.org/doc/index Demonstrates how to extend an existing class in YueScript using the `extends` keyword, enabling inheritance of properties and methods. The example also shows how to override a parent method (`add_item`) and how to call the overridden parent method using `super`. ```YueScript class BackPack extends Inventory size: 10 add_item: (name) => if #@items > size then error "backpack is full" super name ``` -------------------------------- ### YueScript With Statement: Basic Object Initialization Source: https://yuescript.org/doc/index Demonstrates the basic usage of the `with` statement in YueScript to initialize an object by setting properties and calling methods without repeating the object's name. This example shows property assignment (`.name`), method invocation (`\add_relative`, `\save!`), and accessing properties within the `with` block. ```YueScript with Person! .name = "Oswald" \add_relative my_dad \save! print .name ``` -------------------------------- ### Object Destructuring with Renaming and Shorthand in Yuescript Source: https://yuescript.org/doc/index Shows how to extract values from object-like tables by key. Includes examples of renaming extracted variables and using the shorthand `:` prefix when the variable name matches the key, as well as mixing both syntaxes. ```Yuescript obj = { hello: "world" day: "tuesday" length: 20 } {hello: hello, day: the_day} = obj print hello, the_day :day = obj -- OK to do simple destructuring without braces ``` ```Yuescript {:concat, :insert} = table ``` ```Yuescript {:mix, :max, random: rand} = math ``` -------------------------------- ### Yuescript Error Handling with try? Source: https://yuescript.org/doc/index Demonstrates the 'try?' keyword for simplified error handling in Yuescript. It returns the result on success and 'nil' on failure, omitting the boolean status. Examples include usage with nil coalescing, as a function argument, and with an explicit 'catch' block. ```Yuescript a, b, c = try? func! -- with nil coalescing operator a = (try? func!) ?? "default" -- as function argument f try? func! -- with catch block f try? print 123 func! catch e print e e ``` -------------------------------- ### For Loop - As an Expression with Break Return Value Source: https://yuescript.org/doc/index Demonstrates using 'break' with a return value within a 'for' loop expression, allowing the loop to exit early and return a meaningful result. The example finds the first number greater than 10. ```Yuescript first_large = for n in *numbers break n if n > 10 ``` -------------------------------- ### Continue Statement - Basic Usage in Loops Source: https://yuescript.org/doc/index Explains the 'continue' statement, which skips the current iteration of a loop and proceeds to the next. The example demonstrates printing only odd numbers within a loop. ```Yuescript i = 0 while i < 10 i += 1 continue if i % 2 == 0 print i ``` -------------------------------- ### For Loop - As an Expression with Accumulation Source: https://yuescript.org/doc/index Explains how 'for' loops can be used as expressions, where the last statement in the body is coerced into an expression and accumulated into an array table. The example doubles even numbers. ```Yuescript doubled_evens = for i = 1, 20 if i % 2 == 0 i * 2 else i ``` -------------------------------- ### YueScript Do Expression: Combining Multiple Lines Source: https://yuescript.org/doc/index Demonstrates `do` as an expression, allowing multiple lines of code to be combined into a single expression. The result of the `do` expression is the value of its last statement. This example creates a counter closure. ```YueScript counter = do i = 0 -> i += 1 i print counter! print counter! ``` -------------------------------- ### Yuescript Table Field Matching and Conditional Destructuring Source: https://yuescript.org/doc/index Shows how to match against specific fields within a table and conditionally destructure them based on their values. This example uses boolean checks (`success: true`) and captures associated result fields. ```Yuescript switch tb when success: true, :result print "success", result when success: false print "failed", result else print "invalid" ``` -------------------------------- ### YueScript Language Features: Imports, Literals, Comprehension, Pipe, Metatables Source: https://yuescript.org/doc/index This comprehensive example showcases core YueScript language features. It includes import syntax, object and array literals, functional programming constructs like list comprehension (map, filter, reduce), the pipe operator for chaining operations, metatable manipulation, and JavaScript-like export syntax for modules. ```YueScript -- import syntax import p, to_lua from "yue" -- object literals inventory = equipment: - "sword" - "shield" items: - name: "potion" count: 10 - name: "bread" count: 3 -- list comprehension map = (arr, action) -> [action item for item in *arr] filter = (arr, cond) -> [item for item in *arr when cond item] reduce = (arr, init, action): init -> init = action init, item for item in *arr -- pipe operator [1, 2, 3] |> map (x) -> x * 2 |> filter (x) -> x > 4 |> reduce 0, (a, b) -> a + b |> print -- metatable manipulation apple = size: 15 : color: 0x00ffff with apple p .size, .color, . if .<>? -- js-like export syntax export πŸŒ› = "ζœˆδΉ‹θ„šζœ¬" ``` -------------------------------- ### Yuescript Basic Variable Assignment Source: https://yuescript.org/doc/index Illustrates fundamental variable assignment in Yuescript. Variables are dynamically typed and are defined as local by default. Examples include single variable assignment, multiple variable assignment, and re-assignment to existing variables. ```Yuescript hello = "world" a, b, c = 1, 2, 3 hello = 123 -- uses the existing variable ``` -------------------------------- ### Yuescript Switch Statement as an Expression Source: https://yuescript.org/doc/index Illustrates how a Yuescript switch statement can be used as an expression, where its evaluated result is assigned to a variable. This example shows different return values based on 'when' conditions and an 'else' block for handling unmatchable scenarios or errors. ```Yuescript b = 1 next_number = switch b when 1 2 when 2 3 else error "can't count that high!" ``` -------------------------------- ### Generating Macros with Macros in YueScript Source: https://yuescript.org/doc/index Explains how YueScript allows for advanced compile-time code generation by defining macros that produce other macros. This example creates an `Enum` macro that generates a type-checking macro (`BodyType`), ensuring valid enum values at compile time. ```YueScript macro Enum = (...) -> items = {...} itemSet = {item, true for item in *items} (item) -> error "got \"#{item}\", expecting one of #{table.concat items, ', '}" unless itemSet[item] "\"#{item}\"" macro BodyType = $Enum( Static Dynamic Kinematic ) print "Valid enum type:", $BodyType Static -- print "Compilation error with enum type:", $BodyType Unknown ``` -------------------------------- ### Controlling Specific Variable Updates with 'using' in YueScript Source: https://yuescript.org/doc/index This YueScript example illustrates how to explicitly specify which variables from the enclosing scope a function is allowed to modify using the '(add using k, i)' syntax. It shows that 'tmp' is created as a new local variable, while 'k' and 'i' are updated in the outer scope. ```YueScript tmp = 1213 i, k = 100, 50 my_func = (add using k, i) -> tmp = tmp + add -- a new local tmp is created i += tmp k += tmp my_func(22) print i, k -- these have been updated ``` -------------------------------- ### Apply Constructor Property Promotion to Functions in Yuescript Source: https://yuescript.org/doc/index Demonstrates how constructor property promotion can be applied to functions in Yuescript, providing a concise way to initialize object fields directly from function arguments, similar to class constructors. ```Yuescript new = (@fieldA, @fieldB) => @ obj = new {}, 123, "abc" print obj ``` -------------------------------- ### Create class instances and invoke methods in YueScript Source: https://yuescript.org/doc/index Illustrates how to instantiate a YueScript class by calling its name as a function. It also shows the syntax for invoking methods on an instance using the `\` operator, which correctly passes the instance as the first argument to the method. ```YueScript inv = Inventory! inv\add_item "t-shirt" inv\add_item "pants" ``` -------------------------------- ### Yuescript Table Comprehension: Copying Key-Value Pairs Source: https://yuescript.org/doc/index Introduces table comprehensions, showing how to copy all key-value pairs from an existing table into a new one using `pairs` for iteration. ```Yuescript thing = { color: "red" name: "fast" width: 123 } thing_copy = {k, v for k, v in pairs thing} ``` -------------------------------- ### Yuescript List Slicing: Omitting Maximum Bound Source: https://yuescript.org/doc/index Demonstrates list slicing where the maximum index bound is omitted, defaulting to the end of the table, useful for taking elements from a specific start index to the end. ```Yuescript slice = [item for item in *items[2,]] ``` -------------------------------- ### Basic Table Matching and Destructuring in Yuescript Source: https://yuescript.org/doc/index Demonstrates how to use `switch when` to match and destructure tables based on the presence of specific keys. It shows how to extract values from matched structures into local variables. ```Yuescript items = * x: 100 y: 200 * width: 300 height: 400 for item in *items switch item when :x, :y print "Vec2 #{x}, #{y}" when :width, :height print "size #{width}, #{height}" ``` -------------------------------- ### Loading YueScript Entry Files as Lua Modules Source: https://yuescript.org/doc/index Demonstrates the simplest way to integrate YueScript into a Lua project by requiring a `.yue` entry file directly. This method handles on-the-fly compilation and ensures correct line number reporting in error messages. ```Lua require("yue")("your_yuescript_entry") ``` -------------------------------- ### Utilize Constructor Property Promotion in Yuescript Classes Source: https://yuescript.org/doc/index Explains Yuescript's constructor property promotion syntax, which significantly reduces boilerplate code by allowing direct assignment of constructor arguments to instance ('@') and class ('@@') variables upon object instantiation. ```Yuescript class Something new: (@foo, @bar, @@biz, @@baz) => -- Which is short for class Something new: (foo, bar, biz, baz) => @foo = foo @bar = bar @@biz = biz @@baz = baz ``` -------------------------------- ### Demonstrating Destructive Assignment in YueScript Source: https://yuescript.org/doc/index This YueScript example illustrates how a variable 'i' declared in an outer scope can be accidentally overwritten within a function, leading to unintended side effects. It highlights the need for mechanisms to control variable assignment. ```YueScript i = 100 -- many lines of code... my_func = -> i = 10 while i > 0 print i i -= 1 my_func! print i -- will print 0 ``` -------------------------------- ### Execute YueScript Code from File Source: https://yuescript.org/doc/index Loads YueScript code from a file into a function and immediately executes it. Overloads allow specifying an environment table and compiler configuration. ```APIDOC dofile: function(filename: string, env: table, config?: Config): any... Parameters: filename: string - The file name. env: table - The environment table. config: Config - [Optional] The compiler options. Returns: any... - The return values of the loaded function. dofile: function(filename: string, config?: Config): any... Parameters: filename: string - The file name. config: Config - [Optional] The compiler options. Returns: any... - The return values of the loaded function. ``` -------------------------------- ### Continue Statement - With Loop Expressions for Filtering Source: https://yuescript.org/doc/index Demonstrates how 'continue' can be used with loop expressions to prevent specific iterations from being accumulated into the result table, effectively filtering the output. The example filters an array to include only even numbers. ```Yuescript my_numbers = [1, 2, 3, 4, 5, 6] odds = for x in *my_numbers continue if x % 2 == 1 x ``` -------------------------------- ### Define a basic class with constructor and methods in YueScript Source: https://yuescript.org/doc/index Demonstrates the fundamental syntax for defining a class in YueScript. It includes a constructor (`new`) to initialize instance properties and a method (`add_item`) to manipulate them. The `@` prefix is used as shorthand for `self.` to access instance variables. ```YueScript class Inventory new: => @items = {} add_item: (name) => if @items[name] @items[name] += 1 else @items[name] = 1 ``` -------------------------------- ### Exporting and Importing Macros in YueScript Source: https://yuescript.org/doc/index Demonstrates how to define and export macros from one YueScript file (`utils.yue`) and then import and use them in another (`main.yue`). It showcases symbol import, renaming, and piping with custom macros for functional programming patterns. ```YueScript -- file: utils.yue export macro map = (items, action) -> "[#{action} for _ in *#{items}]" export macro filter = (items, action) -> "[_ for _ in *#{items} when #{action}]" export macro foreach = (items, action) -> "for _ in *#{items} #{action}" -- file main.yue import "utils" as { $, -- symbol to import all macros $foreach: $each -- rename macro $foreach to $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` -------------------------------- ### Load YueScript Code from File Source: https://yuescript.org/doc/index Loads YueScript code from a file into a function. Overloads allow specifying an environment table and compiler configuration. ```APIDOC loadfile: function(filename: string, env: table, config?: Config): nil | function(...: any): (any...), string | nil Parameters: filename: string - The file name. env: table - The environment table. config: Config - [Optional] The compiler options. Returns: function | nil - The loaded function, or nil if the loading failed. string | nil - The error message, or nil if the loading succeeded. loadfile: function(filename: string, config?: Config): nil | function(...: any): (any...), string | nil Parameters: filename: string - The file name. config: Config - [Optional] The compiler options. Returns: function | nil - The loaded function, or nil if the loading failed. string | nil - The error message, or nil if the loading succeeded. ``` -------------------------------- ### Yuescript Module Import Syntax Source: https://yuescript.org/doc/index Demonstrates various ways to import modules and specific items in Yuescript. This includes table destructuring for specific functions, implicit requiring of modules, Python-style imports, and aliasing for modules or destructured items. ```Yuescript -- used as table destructuring do import insert, concat from table -- report error when assigning to insert, concat import C, Ct, Cmt from require "lpeg" -- shortcut for implicit requiring import x, y, z from 'mymodule' -- import with Python style from 'module' import a, b, c -- shortcut for requring a module do import 'module' import 'module_x' import "d-a-s-h-e-s" import "module.part" -- requring module with aliasing or table destructuring do import "player" as PlayerModule import "lpeg" as :C, :Ct, :Cmt import "export" as {one, two, Something:{umm:{ch}}} ``` -------------------------------- ### Yuescript Explicit Local Variable Declaration Source: https://yuescript.org/doc/index Explains how to explicitly declare local variables in Yuescript. This includes using `local *` to forward declare all variables within a `do` block as locals, and `local ^` to forward declare only variables starting with an uppercase letter as locals. ```Yuescript do local a = 1 local * print "forward declare all variables as locals" x = -> 1 + y + z y, z = 2, 3 global instance = Item\new! do local X = 1 local ^ print "only forward declare upper case variables" a = 1 B = 2 ``` -------------------------------- ### For Loop - Shorter Single-Line Syntax Source: https://yuescript.org/doc/index Illustrates the concise single-line syntax for 'for' loops using the 'do' keyword, applicable to all loop variations when the body consists of a single statement. ```Yuescript for item in *items do print item for j = 1, 10, 3 do print j ``` -------------------------------- ### For Loop - Basic Numeric and Generic Iteration Source: https://yuescript.org/doc/index Demonstrates the two primary forms of 'for' loops in Yuescript: numeric iteration with an optional step, and generic iteration over key-value pairs of an object. ```Yuescript for i = 10, 20 print i for k = 1, 15, 2 -- an optional step provided print k for key, value in pairs object print key, value ``` -------------------------------- ### Preventing Destructive Assignment with 'using nil' in YueScript Source: https://yuescript.org/doc/index This YueScript example demonstrates the use of '(using nil)' in a function definition. It shows how 'using nil' prevents a function from overwriting variables from its enclosing scope, instead creating a new local variable if an assignment with the same name occurs. ```YueScript i = 100 my_func = (using nil) -> i = "hello" -- a new local variable is created here my_func! print i -- prints 100, i is unaffected ``` -------------------------------- ### Yuescript Function Definition with Arguments Source: https://yuescript.org/doc/index Shows how to define functions in Yuescript that accept arguments. Arguments are listed in parentheses before the '->' arrow, allowing the function to operate on provided inputs. ```Yuescript sum = (x, y) -> print "sum", x + y ``` -------------------------------- ### Multiline Function Chaining in YueScript Source: https://yuescript.org/doc/index Demonstrates how to write multi-line chained function calls in YueScript. It highlights the importance of consistent indentation for readability and correct parsing, allowing complex operations to be expressed clearly. ```YueScript Rx.Observable .fromRange 1, 8 \filter (x) -> x % 2 == 0 \concat Rx.Observable.of 'who do we appreciate' \map (value) -> value .. '!' \subscribe print ``` -------------------------------- ### Illustrate shared mutable class property issue in YueScript Source: https://yuescript.org/doc/index Highlights a common pitfall in OOP where mutable properties declared directly within a class are shared across all instances. This example demonstrates how modifications to such a property in one instance can unintentionally affect other instances, leading to unexpected behavior. ```YueScript class Person clothes: [] give_item: (name) => table.insert @clothes, name a = Person! b = Person! a\give_item "pants" b\give_item "shirt" -- will print both pants and shirt print item for item in *a.clothes ``` -------------------------------- ### Yuescript List Comprehension: Doubling Values Source: https://yuescript.org/doc/index Demonstrates a basic list comprehension in Yuescript to create a new list where each element from the original list is doubled. It iterates using `ipairs` for numeric indexing. ```Yuescript items = [ 1, 2, 3, 4 ] doubled = [item * 2 for i, item in ipairs items] ``` -------------------------------- ### Define a function with default arguments in Yuescript Source: https://yuescript.org/doc/index Illustrates how to provide default values for function arguments in Yuescript. Any `nil` arguments are replaced by their defaults before the function body executes, ensuring arguments always have a value. ```Yuescript my_function = (name = "something", height = 100) -> print "Hello I am", name print "My height is", height ``` -------------------------------- ### Yuescript Table Comprehension: Unpacking Tuples into Key-Value Pairs Source: https://yuescript.org/doc/index Illustrates converting a list of two-element tuples into a table, where each tuple's first element becomes the key and the second becomes the value, using `unpack`. ```Yuescript tuples = [ ["hello", "world"], ["foo", "bar"]] tbl = {unpack tuple for tuple in *tuples} ``` -------------------------------- ### Correctly initialize mutable instance properties in YueScript Source: https://yuescript.org/doc/index Provides the recommended approach for handling mutable instance state in YueScript classes. By initializing mutable properties within the class's constructor (`new`), each instance receives its own independent copy, preventing unintended side effects from shared state. ```YueScript class Person new: => @clothes = [] ``` -------------------------------- ### Load YueScript Code from String Source: https://yuescript.org/doc/index Loads YueScript code from a string into a function. Multiple overloads are available to specify chunk name, environment table, and compiler configuration. ```APIDOC loadstring: function(input: string, chunkname: string, env: table, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil Parameters: input: string - The YueScript code. chunkname: string - The name of the code chunk. env: table - The environment table. config: Config - [Optional] The compiler options. Returns: function | nil - The loaded function, or nil if the loading failed. string | nil - The error message, or nil if the loading succeeded. loadstring: function(input: string, chunkname: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil Parameters: input: string - The YueScript code. chunkname: string - The name of the code chunk. config: Config - [Optional] The compiler options. Returns: function | nil - The loaded function, or nil if the loading failed. string | nil - The error message, or nil if the loading succeeded. loadstring: function(input: string, config?: Config): --[[loaded function]] nil | function(...: any): (any...), --[[error]] string | nil Parameters: input: string - The YueScript code. config: Config - [Optional] The compiler options. Returns: function | nil - The loaded function, or nil if the loading failed. string | nil - The error message, or nil if the loading succeeded. ``` -------------------------------- ### YueScript Library Core API Source: https://yuescript.org/doc/index The core API for the YueScript language library, accessible via 'require("yue")'. It provides functionalities for versioning, file system interaction, code compilation, and loader management. ```APIDOC yue: The YueScript language library. version: string Description: The YueScript version. dirsep: string Description: The file separator for the current platform. yue_compiled: {string: string} Description: The compiled module code cache. to_lua: function(code: string, config?: Config): --[[codes]] string | nil, --[[error]] string | nil, --[[globals]] {{string, integer, integer}} | nil Description: The YueScript compiling function. It compiles the YueScript code to Lua code. Parameters: code (string): The YueScript code. config (Config, optional): The compiler options. Returns: string | nil: The compiled Lua code, or nil if the compilation failed. string | nil: The error message, or nil if the compilation succeeded. {{string, integer, integer}} | nil: The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. file_exist: function(filename: string): boolean Description: The source file existence checking function. Can be overridden to customize the behavior. Parameters: filename (string): The file name. Returns: boolean: Whether the file exists. read_file: function(filename: string): string Description: The source file reading function. Can be overridden to customize the behavior. Parameters: filename (string): The file name. Returns: string: The file content. insert_loader: function(pos?: integer): boolean Description: Insert the YueScript loader to the package loaders (searchers). Parameters: pos (integer, optional): The position to insert the loader. Default is 3. Returns: boolean: Whether the loader is inserted successfully. It will fail if the loader is already inserted. ``` -------------------------------- ### Yuescript Table Comprehension: Filtering Keys Source: https://yuescript.org/doc/index Demonstrates filtering key-value pairs in a table comprehension using a `when` clause, allowing specific keys to be excluded from the new table. ```Yuescript no_color = {k, v for k, v in pairs thing when k != "color"} ``` -------------------------------- ### Yuescript Function Call Chaining and Argument Application Source: https://yuescript.org/doc/index Illustrates how arguments are applied to the closest function when chaining multiple function calls in Yuescript. It highlights potential ambiguities and the need for explicit parentheses in complex expressions. ```Yuescript sum 10, 20 print sum 10, 20 a b c "a", "b", "c" ``` -------------------------------- ### Yuescript Switch with Single-Line When Blocks using 'then' Source: https://yuescript.org/doc/index Shows how to write compact 'when' and 'else' blocks in a Yuescript switch statement by utilizing the 'then' keyword for single-line 'when' clauses. This approach reduces verbosity for simple actions or return values. ```Yuescript msg = switch math.random(1, 5) when 1 then "you are lucky" when 2 then "you are almost lucky" else "not so lucky" ``` -------------------------------- ### Matching Array Elements in Yuescript Switch Statements Source: https://yuescript.org/doc/index Explains how to match against specific array elements and patterns within a `switch when` statement. It demonstrates capturing individual elements and assigning default values to captured variables if the element is not present. ```Yuescript switch tb when [1, 2, 3] print "1, 2, 3" when [1, b, 3] print "1, #{b}, 3" when [1, 2, b = 3] -- b has a default value print "1, 2, #{b}" ``` -------------------------------- ### Yuescript Table Comprehension: Generating Key-Value Pairs with `*` Source: https://yuescript.org/doc/index Shows how the `*` operator can be used in table comprehensions to iterate over a list of values and generate key-value pairs, such as creating a lookup table for square roots. ```Yuescript numbers = [1, 2, 3, 4] sqrts = {i, math.sqrt i for i in *numbers} ``` -------------------------------- ### Commenting Syntax and Usage in YueScript Source: https://yuescript.org/doc/index Illustrates single-line (`--`) and multi-line (`--[[ ... ]]--`) comment syntax in YueScript. It also shows how comments can be embedded within expressions for inline documentation or temporary disabling of code parts. ```YueScript -- I am a comment str = --[[ This is a multi-line comment. It's OK. ]] strA \ -- comment 1 .. strB \ -- comment 2 .. strC func --[[port]] 3000, --[[ip]] "192.168.1.1" ``` -------------------------------- ### Yuescript Basic Function Definition Source: https://yuescript.org/doc/index Introduces the fundamental syntax for defining functions in Yuescript using the '->' arrow operator. It shows how to declare an empty function and subsequently call it. ```Yuescript my_function = -> my_function() -- call the empty function ``` -------------------------------- ### Yuescript Direct Export to Module Table Source: https://yuescript.org/doc/index Demonstrates how to directly add items to the exported module table without creating corresponding local variables. This is useful for exporting properties using dot notation or bracket notation for dynamic keys. ```Yuescript export.itemA = tb export. = items export["a-b-c"] = 123 ``` -------------------------------- ### Conditional Logic in Yuescript Functions and Assignments Source: https://yuescript.org/doc/index Explains how `if` statements can be integrated into function definitions and used for assigning values to variables. This demonstrates the flexibility of conditionals in Yuescript for building dynamic logic. ```Yuescript is_tall = (name) -> if name == "Rob" true else false message = if is_tall "Rob" "I am very tall" else "I am not so tall" print message -- prints: I am very tall ``` -------------------------------- ### Repeat Loop - Basic Usage Source: https://yuescript.org/doc/index Shows the 'repeat...until' loop construct, which executes its body at least once and continues iterating until the specified condition becomes true. ```Yuescript i = 10 repeat print i i -= 1 until i == 0 ``` -------------------------------- ### Perform Class Mixing with 'using' Keyword in Yuescript Source: https://yuescript.org/doc/index Explains Yuescript's 'using' keyword for class mixing, which allows incorporating functions from plain tables or existing class objects into a new class. It also highlights considerations for overriding the '__index' metamethod when mixing with tables. ```Yuescript MyIndex = __index: var: 1 class X using MyIndex func: => print 123 x = X! print x.var class Y using X y = Y! y\func! assert y.__class.__parent ~= X -- X is not parent of Y ``` -------------------------------- ### YueScript Compiler Configuration Options Source: https://yuescript.org/doc/index Defines the various options available for configuring the YueScript compiler, including settings for global variable linting. These options control aspects of the compilation process. ```APIDOC Config: - Description: The compiler compile options. - Fields: - lint_global: boolean - Description: Whether the compiler should collect the global variables appearing in the code. ``` -------------------------------- ### Define Basic Yuescript Backcall Source: https://yuescript.org/doc/index Demonstrates the fundamental syntax for defining a backcall in Yuescript using the `<-` arrow. This construct un-nests callbacks by implicitly filling in a function call as the last parameter. The compiled Lua output is also shown. ```Yuescript <- f print "hello" ``` ```Lua <- f print "hello" ``` -------------------------------- ### Programmatic YueScript to Lua Compilation with `yue.to_lua` Source: https://yuescript.org/doc/index Shows how to use the `yue.to_lua` function to compile YueScript code strings into Lua code directly within a Lua environment. It highlights various compilation options such as implicit return roots, line number preservation, global linting, and target Lua version. ```Lua local yue = require("yue") local codes, err, globals = yue.to_lua([[ f = -> print "hello world" f! ]],{ implicit_return_root = true, reserve_line_number = true, lint_global = true, space_over_tab = false, options = { target = "5.4", path = "/script" } }) ``` -------------------------------- ### Yuescript List Slicing: Specifying Minimum and Maximum Bounds Source: https://yuescript.org/doc/index Explains how to use slicing with the `*` operator to extract a sub-list based on explicit minimum and maximum index bounds, inclusive of both. ```Yuescript slice = [item for item in *items[1, 5]] ``` -------------------------------- ### Advanced YueScript Module Loading with Custom Error Tracing Source: https://yuescript.org/doc/index Illustrates a more controlled approach to loading YueScript modules in Lua. It involves manually inserting the YueScript loader and using `xpcall` to catch errors, providing a custom traceback function (`yue.traceback`) for detailed debugging. ```Lua local yue = require("yue") yue.insert_loader() local success, result = xpcall(function() return require("yuescript_module_name") end, function(err) return yue.traceback(err) end) ``` -------------------------------- ### Yuescript List Slicing: Omitting Minimum Bound and Using Step Source: https://yuescript.org/doc/index Shows how to slice a list by omitting the minimum bound (defaults to 1) and specifying a step size, allowing extraction of elements at regular intervals (e.g., odd-indexed items). ```Yuescript slice = [item for item in *items[,,2]] ``` -------------------------------- ### Yuescript List Comprehension: Nested Loops for Cartesian Product Source: https://yuescript.org/doc/index Demonstrates how to use multiple `for` clauses in a list comprehension to achieve nested loop behavior, effectively generating a Cartesian product of two lists. ```Yuescript x_coords = [4, 5, 6, 7] y_coords = [9, 2, 3] points = [ [x, y] for x in *x_coords \ for y in *y_coords] ``` -------------------------------- ### Yuescript Chaining Assignment Source: https://yuescript.org/doc/index Shows how to perform chaining assignments in Yuescript, allowing multiple variables to be assigned the same value in a single statement. This is a concise way to initialize several variables to an identical value or the result of a function call. ```Yuescript a = b = c = d = e = 0 x = y = z = f! ``` -------------------------------- ### Yuescript List Slicing: Reversing Order with Negative Step Source: https://yuescript.org/doc/index Demonstrates using a negative step size in slicing to iterate and extract elements in reverse order from a specified range. ```Yuescript reverse_slice = [item for item in *items[-1,1,-1]] ``` -------------------------------- ### For Loop as a Line Decorator in Yuescript Source: https://yuescript.org/doc/index Shows how `for` loops can be concisely applied as line decorators for iterating over collections. This compact syntax is useful for simple loop bodies. ```Yuescript print "item: ", item for item in *items ``` -------------------------------- ### Chaining Comparison Operators in YueScript Source: https://yuescript.org/doc/index Illustrates how comparison operators can be arbitrarily chained in YueScript, allowing for concise and readable expressions. This feature simplifies complex conditional logic by combining multiple comparisons into a single line. ```YueScript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 -- output: true a = 5 print 1 <= a <= 10 -- output: true ``` -------------------------------- ### Use Yuescript Backcalls with `do` Statement for Sequential Operations Source: https://yuescript.org/doc/index Demonstrates how to use a `do` statement to group multiple asynchronous operations involving backcalls. This allows for sequential execution of operations and enables further code to execute after the backcall sequence, improving control flow for chained operations. ```Yuescript result, msg = do data <- readAsync "filename.txt" print data info <- processAsync data check info print result, msg ``` ```Lua result, msg = do data <- readAsync "filename.txt" print data info <- processAsync data check info print result, msg ``` -------------------------------- ### Basic Array Destructuring in Yuescript Source: https://yuescript.org/doc/index Illustrates how to unpack values from an array-like table into individual variables based on their position using destructuring assignment. ```Yuescript thing = [1, 2] [a, b] = thing print a, b ``` -------------------------------- ### Basic Yuescript Switch Statement with Assignment Source: https://yuescript.org/doc/index Demonstrates the fundamental structure of a Yuescript switch statement, including an assignment expression within the switch condition, multiple 'when' clauses for matching against several values, and an 'else' block for unmatched cases. Comparison is performed using the '==' operator. ```Yuescript switch name := "Dan" when "Robert" print "You are Robert" when "Dan", "Daniel" print "Your name, it's Dan" else print "I don't know about you with name #{name}" ``` -------------------------------- ### While and Until Loops as Line Decorators in Yuescript Source: https://yuescript.org/doc/index Demonstrates the use of `while` and `until` loops as line decorators for compact conditional looping. `while` continues as long as the condition is true, and `until` continues until the condition becomes true. ```Yuescript game\update! while game\isRunning! reader\parse_line! until reader\eof! ``` -------------------------------- ### Demonstrate nested multi-line function arguments in Yuescript Source: https://yuescript.org/doc/index Illustrates how multi-line function invocations can be nested in Yuescript. The level of indentation is crucial for the parser to determine to which function the arguments belong, maintaining clarity in complex calls. ```Yuescript my_func 5, 6, 7, 6, another_func 6, 7, 8, 9, 1, 2, 5, 4 ``` -------------------------------- ### Error Handling with Try-Catch Blocks in YueScript Source: https://yuescript.org/doc/index Details the `try-catch` syntax for robust error handling in YueScript. It covers capturing errors, returning success/result pairs, and integrating `try` blocks with `if` assignment patterns for conditional execution based on operation outcome. ```YueScript try func 1, 2, 3 catch err print yue.traceback err success, result = try func 1, 2, 3 catch err yue.traceback err try func 1, 2, 3 catch err print yue.traceback err success, result = try func 1, 2, 3 try print "trying" func 1, 2, 3 -- working with if assignment pattern if success, result := try func 1, 2, 3 catch err print yue.traceback err print result ``` -------------------------------- ### Yuescript Explicit Function Return Source: https://yuescript.org/doc/index Shows how to use the 'return' keyword in Yuescript functions for explicit control over what value is returned, overriding the implicit return behavior. ```Yuescript sum = (x, y) -> return x + y ```