### YueScript Command-Line Tool (yue) Reference Source: https://github.com/ippclub/yuescript/blob/main/README.md Comprehensive documentation for the `yue` command-line tool, detailing its various options for compiling, executing, and managing YueScript files. It includes flags for output control, debugging, specific Lua version targeting, and practical usage examples. ```APIDOC Usage: yue [options|files|directories] ... Options: -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 (does not 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) Extended Options: --target=version: Specify the Lua version that codes will be generated to (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 REPL Mode: Execute without options to enter REPL, type symbol '$' in a single line to start/stop multi-line mode Usage Examples: Recursively compile every YueScript file with extension .yue under current path: yue . Compile and save results to a target path: yue -t /target/path/ . Compile and reserve debug info: yue -l . Compile and generate minified codes: yue -m . Execute raw codes: yue -e 'print 123' Execute a YueScript file: yue -e main.yue ``` -------------------------------- ### Build and Install YueScript Binary Tool Source: https://github.com/ippclub/yuescript/blob/main/README.md Commands to compile and install the YueScript standalone command-line binary tool from source. This provides the `yue` utility for direct use, with options to disable macro features or built-in Lua binaries during compilation. ```Shell make install ``` ```Shell make install NO_MACRO=true ``` ```Shell make install NO_LUA=true ``` -------------------------------- ### Install YueScript via LuaRocks or Build from Source Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Instructions for installing YueScript as a Lua module using LuaRocks, building the shared library (`yue.so`) from source, and compiling the YueScript binary tool. It includes options to build without macro features or without a built-in Lua binary. ```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 ``` -------------------------------- ### Inserting YueScript and Lua Code via Macros Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This example illustrates how YueScript macros can directly insert code into the compiled output. Macros can return strings containing YueScript code or configuration tables for Lua code. It highlights that variables defined by macro-generated code are not directly accessible from the calling scope and demonstrates inserting raw Lua code blocks. ```moonscript macro yueFunc = (var) -> "local #{var} = ->" $yueFunc funcA funcA = -> "无法访问宏生成月之脚本里定义的变量" macro luaFunc = (var) -> { code: "local function #{var}() end" type: "lua" } $luaFunc funcB funcB = -> "无法访问宏生成 Lua 代码里定义的变量" macro lua = (code) -> { :code type: "lua" } -- raw字符串的开始和结束符号会自动被去除了再传入宏函数 $lua[==[ -- 插入原始Lua代码 if cond then print("输出") end ]==] ``` -------------------------------- ### Install YueScript Lua Module with LuaRocks Source: https://github.com/ippclub/yuescript/blob/main/README.md Command to install the YueScript Lua module using LuaRocks, the official package manager for Lua modules. This method simplifies the installation and dependency management for Lua projects. ```Shell luarocks install yuescript ``` -------------------------------- ### YueScript Development and Build Commands Source: https://github.com/ippclub/yuescript/blob/main/doc/README.md These commands are used to manage the development and build processes for the YueScript project. `yarn dev` typically starts a local development server, while `yarn build` compiles the project for deployment or distribution. ```bash yarn dev yarn build ``` -------------------------------- ### Build YueScript Lua Module Shared Library Source: https://github.com/ippclub/yuescript/blob/main/README.md Instructions to compile the YueScript Lua module (`yue.so`) from source using `make`. This process creates a shared library that can be loaded and used within Lua applications. ```Shell make shared LUAI=/usr/local/include/lua LUAL=/usr/local/lib/lua ``` -------------------------------- ### Require and Compile YueScript Code in Lua Source: https://github.com/ippclub/yuescript/blob/main/README.md Lua code demonstrating how to load the YueScript module and compile YueScript source code into Lua at runtime. It showcases options for controlling implicit returns, preserving line numbers for debugging, and linting global variables. ```Lua require("yue")("main") -- require `main.yue` 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 }) ``` -------------------------------- ### Using `with` in Function Definitions in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how `with` can be integrated into a function to streamline object creation and initialization. This example creates a `Person` object, sets its name, and adds relatives within a `create_person` function. ```moonscript create_person = (name, relatives) -> with Person! .name = name \add_relative relative for relative in *relatives me = create_person "Leaf", [dad, mother, sister] ``` -------------------------------- ### Defining and Using Basic Macros in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This snippet demonstrates fundamental macro definition and usage. It shows how to create simple constant-like macros (PI2, HELLO), macros that accept parameters (config, asserts, assert) for conditional code generation, and how macros can process arguments as strings (and) for compile-time expression manipulation. ```moonscript macro PI2 = -> math.pi * 2 area = $PI2 * 5 macro HELLO = -> "'你好 世界'" print $HELLO macro config = (debugging) -> global debugMode = debugging == "true" "" macro asserts = (cond) -> debugMode and "assert #{cond}" or "" macro assert = (cond) -> debugMode and "assert #{cond}" or "#{cond}" $config true $asserts item ~= nil $config false value = $assert item -- 宏函数参数传递的表达式会被转换为字符串 macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" ``` -------------------------------- ### Instantiate a class and call methods in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This example shows how to create an instance of a previously defined class (e.g., `Inventory`) by calling the class name as a function (`Inventory!`). It then demonstrates how to invoke methods on the instance using the `\` operator, which correctly passes the instance as the first argument to the method. ```moonscript inv = Inventory! inv\add_item "t-shirt" inv\add_item "pants" ``` -------------------------------- ### Instantiate Same Class from Instance Method in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Provides a quick example of how to create a new instance of the same class from within an instance method using the `@@` alias. This allows for convenient factory-like patterns or self-replication within class logic. ```moonscript some_instance_method = (...) => @@ ... ``` -------------------------------- ### Create Metatables and Metamethods in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Explains how to create metatables and define metamethods using the `<>` operator in Moonscript. It shows examples of setting up `__add` for custom arithmetic operations and defining fields with variable names. ```moonscript mt = {} add = (right) => <>: mt, value: @value + right.value mt.__add = add a = <>: mt, value: 1 -- set field with variable of the same name b = :, value: 2 c = : mt.__add, value: 3 d = a + b + c print d.value close _ = : -> print "out of scope" ``` -------------------------------- ### Core YueScript CMake Project Setup Source: https://github.com/ippclub/yuescript/blob/main/CMakeLists.txt This section initializes the CMake project, sets the minimum required CMake version, defines the project name, and configures global include directories and C++ compiler definitions. It also enables C++ as a language for the project and adds a compiler option to suppress deprecated declarations on Apple platforms. ```CMake cmake_minimum_required(VERSION 3.10) project(yue CXX) set(LUA_LIBDIR ${LUA_INCDIR}/../lib ${LUA_INCDIR}/../../lib) set(LUA_INCLUDE_DIR "${LUA_INCDIR}") enable_language(CXX) include_directories(src src/3rdParty ${LUA_INCLUDE_DIR}) add_definitions(-std=c++17 -O3 -fPIC) if (APPLE) add_compile_options(-Wno-deprecated-declarations) endif () ``` -------------------------------- ### Using Built-in YueScript Macros Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This example showcases the usage of YueScript's built-in macros. It specifically demonstrates `$FILE` to retrieve the current module's name and `$LINE` to get the current line number at compile time. It also notes that these built-in macros can be overridden by user-defined macros with the same name. ```moonscript print $FILE -- 获取当前模块名称的字符串 print $LINE -- 获取当前代码行数:2 ``` -------------------------------- ### Using `with` as an Expression in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates how the `with` statement can be used as an expression, returning the value it operates on. This example shows setting an encoding on a file object and assigning the result to a variable. ```moonscript file = with File "favorite_foods.txt" \set_encoding "utf8" ``` -------------------------------- ### Moonscript: Generating Lookup Table with Comprehension and `*` Operator Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates the use of the `*` operator in table comprehensions to iterate over array elements. This example processes a list of numbers to create a lookup table where each number is mapped to its square root. ```moonscript numbers = [1, 2, 3, 4] sqrts = {i, math.sqrt i for i in *numbers} ``` -------------------------------- ### Exporting and Importing Macros in YueScript Modules Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This snippet demonstrates how to organize and reuse macros across different YueScript modules. It shows defining and exporting macros (map, filter, foreach) from a 'utils.yue' file and then importing them into 'main.yue'. It also illustrates importing all macros using '$' and renaming specific imported macros. ```moonscript -- 文件: 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}" -- 文件 main.yue import "utils" as { $, -- 表示导入所有宏的符号 $foreach: $each -- 重命名宏 $foreach 为 $each } [1, 2, 3] |> $map(_ * 2) |> $filter(_ > 4) |> $each print _ ``` -------------------------------- ### Moonscript: Basic Array Slicing with Bounds Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Explains how to restrict iteration over an array using slicing syntax with explicit minimum and maximum bounds. This example selects items with indexes between 1 and 5 inclusive from the `items` array. ```moonscript slice = [item for item in *items[1, 5]] ``` -------------------------------- ### Generating Macros Dynamically in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This advanced example demonstrates the powerful concept of 'macro-generating macros' in YueScript. It defines an `Enum` macro that, when called, generates another macro (e.g., `BodyType`). This generated macro then performs compile-time validation, ensuring that its arguments match predefined enum values, providing robust type-like checking. ```moonscript 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 "有效的枚举类型:", $BodyType Static -- print "编译报错的枚举类型:", $BodyType Unknown ``` -------------------------------- ### Moonscript: Array Slicing with Step Size Only Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates array slicing where only the step size is provided, defaulting the minimum bound to 1 and the maximum to the end of the array. This example extracts all odd-indexed items from the `items` array. ```moonscript slice = [item for item in *items[,,2]] ``` -------------------------------- ### Moonscript: Filtering Table Elements with Comprehension Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how to create a new table from an existing one, excluding specific elements based on a conditional expression. This example filters out the 'color' key, resulting in a table without that entry. ```moonscript no_color = {k, v for k, v in pairs thing when k != "color"} ``` -------------------------------- ### Programmatically Compile YueScript to Lua Code Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how to use the `yue.to_lua` function within Lua to compile YueScript code strings into Lua code. This example includes various compilation options such as `implicit_return_root`, `reserve_line_number`, `lint_global`, `space_over_tab`, and target Lua version/path settings. ```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" } }) ``` -------------------------------- ### Using For Loops as Expressions in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how a for loop can be used as an expression, where the last statement of each iteration is collected into an accumulating array table. This example doubles even numbers within a range. ```moonscript doubled_evens = for i = 1, 20 if i % 2 == 0 i * 2 else i ``` -------------------------------- ### Using Continue Statement in YueScript Loops Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates the `continue` statement, which skips the remainder of the current loop iteration and proceeds to the next one. This example prints only odd numbers. ```moonscript i = 0 while i < 10 i += 1 continue if i % 2 == 0 print i ``` -------------------------------- ### Basic Chained Comparisons in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how YueScript allows arbitrary chaining of comparison operators (e.g., `<`, `<=`, `==`, `>`). It shows examples with literal values and variables, producing boolean results, similar to Python's chained comparisons. ```MoonScript print 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 -- output: true a = 5 print 1 <= a <= 10 -- output: true ``` -------------------------------- ### MoonScript Basic Switch Statement with Assignment Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This example demonstrates the fundamental structure of a MoonScript switch statement. It shows how to use an assignment expression within the switch, handle multiple 'when' conditions, and provide a fallback 'else' block for unmatched values. Comparison is performed using the '==' operator. ```MoonScript 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}" ``` -------------------------------- ### Moonscript: Array Slicing as an Expression Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how array slicing can be used directly as an expression to create a sub-list from an existing table without explicit iteration. This example extracts the 2nd and 4th items into a new list. ```moonscript -- take the 2nd and 4th items as a new list sub_list = items[2, 4] ``` -------------------------------- ### YueScript Operator Aliases and Chaining Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/zh/doc/README.md This snippet highlights YueScript's extensions to standard Lua operators. It demonstrates the `!=` alias for the `~=` (not equal) operator and introduces the `\` or `::` operators for fluent method chaining, allowing for more concise and expressive function calls, especially when dealing with potentially nil objects. ```moonscript tb\func! if tb ~= nil tb::func! if tb != nil ``` -------------------------------- ### Configure CMake for YueScript Library Linking and Compiler Options Source: https://github.com/ippclub/yuescript/blob/main/CMakeLists.txt This snippet configures the CMake build for the 'yue' target. It conditionally links the 'Threads' library if available and adds specific linker options for GNU compilers, such as '-lstdc++fs' and '-ldl'. An empty install code block is also included. ```CMake target_link_libraries(yue PRIVATE ${LUA_LIBRARIES} Threads::Threads) else () target_link_libraries(yue PRIVATE ${LUA_LIBRARIES}) endif() if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_link_options(yue PRIVATE -lstdc++fs -ldl) endif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") install(CODE "") ``` -------------------------------- ### YueScript Comment Syntax Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates single-line and multi-line comments in YueScript, including inline comments within function calls and string concatenations. Multi-line comments are enclosed in `--[[ ... ]]` and single-line comments start with `--`. ```moonscript -- 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" ``` -------------------------------- ### Defining and Using YueScript Macros for Compile-Time Code Generation Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates common patterns for defining macros in YueScript. Macros are functions evaluated at compile time to insert generated code. Examples include constant definitions, conditional code generation based on flags, and string manipulation for dynamic code assembly. ```Moonscript macro PI2 = -> math.pi * 2 area = $PI2 * 5 macro HELLO = -> "'hello world'" print $HELLO macro config = (debugging) -> global debugMode = debugging == "true" "" macro asserts = (cond) -> debugMode and "assert #{cond}" or "" macro assert = (cond) -> debugMode and "assert #{cond}" or "#{cond}" $config true $asserts item ~= nil $config false value = $assert item -- the passed expressions are treated as strings macro and = (...) -> "#{ table.concat {...}, ' and ' }" if $and f1!, f2!, f3! print "OK" ``` -------------------------------- ### Correctly initialize mutable instance properties in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md To avoid the shared mutable state pitfall, this example demonstrates the correct approach: initializing mutable instance properties (like `@clothes`) within the class's constructor (`new`). This ensures that each new instance receives its own independent copy of the property, preventing unintended side effects across instances. ```moonscript class Person new: => @clothes = [] ``` -------------------------------- ### Named Export Syntax in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how to use named exports in YueScript, which define local variables and add corresponding fields to the exported table. Examples cover exporting multiple variables, conditional values, functions, and classes. It also shows named export with destructuring and direct property assignment to the export object. ```moonscript export a, b, c = 1, 2, 3 export cool = "cat" export What = if this "abc" else "def" export y = -> hallo = 3434 export class Something umm: "cool" ``` ```moonscript export :loadstring, to_lua: tolua = yue export {itemA: {:fieldA = 'default'}} = tb ``` ```moonscript export.itemA = tb export. = items export["a-b-c"] = 123 ``` -------------------------------- ### Using `with` for Object Initialization in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates the basic usage of the `with` statement to perform multiple operations (property assignment, method calls) on a newly created object without repeating its name. Shows how to access properties with `.` and call methods with `\`. ```moonscript with Person! .name = "Oswald" \add_relative my_dad \save! print .name ``` -------------------------------- ### Creating Implicit Objects in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how to define implicit objects or lists within table blocks using '*' or '-' symbols. This feature allows for concise data structure definition where fields maintain consistent indentation. Examples include implicit objects in assignments, function calls, return statements, and nested tables. ```moonscript -- assignment with implicit object list = * 1 * 2 * 3 -- function call with implicit object func * 1 * 2 * 3 -- return with implicit object f = -> return * 1 * 2 * 3 -- table with implicit object tb = name: "abc" values: - "a" - "b" - "c" objects: - name: "a" value: 1 func: => @value + 1 tb: fieldA: 1 - name: "b" value: 2 func: => @value + 2 tb: { } ``` -------------------------------- ### Utilize Constructor Property Promotion in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates Moonscript's constructor property promotion feature, allowing concise declaration and assignment of instance (`@`) and class (`@@`) variables directly in the `new` method signature, significantly reducing boilerplate code for simple value objects. ```moonscript 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 ``` -------------------------------- ### Basic For Loop Syntax in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates the two primary forms of for loops in YueScript: numeric iteration with optional step, and generic iteration over key-value pairs using `pairs`. ```moonscript 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 ``` -------------------------------- ### Filtering Loop Expressions with Continue in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how `continue` can be used within a loop expression to filter out iterations, preventing them from being accumulated into the result array. This example filters for even numbers. ```moonscript my_numbers = [1, 2, 3, 4, 5, 6] odds = for x in *my_numbers continue if x % 2 == 1 x ``` -------------------------------- ### Initialize Object Fields with Constructor Function in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates using a function with constructor property promotion syntax to initialize an object's fields. This pattern allows for flexible object creation and field assignment outside of a formal class constructor. ```moonscript new = (@fieldA, @fieldB) => @ obj = new {}, 123, "abc" print obj ``` -------------------------------- ### YueScript Command Line Interface (CLI) Reference Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Detailed reference for the `yue` command-line tool, listing all available options for compilation, execution, and debugging of YueScript files. Includes parameters, their functions, and common use cases for interacting with the compiler. ```APIDOC yue [options|files|directories] ... Options: -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 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. ``` -------------------------------- ### Moonscript: Array Slicing with Negative Bounds Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates the use of negative bounds in array slicing, which count from the end of the table. This example selects the last four items from the `items` array. ```moonscript -- take the last 4 items slice = [item for item in *items[-4,-1]] ``` -------------------------------- ### Call MoonScript Functions with Arguments and Chaining Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how to invoke MoonScript functions by listing arguments after the function name. It also illustrates function call chaining, where arguments apply to the closest function on the left. ```moonscript sum 10, 20 print sum 10, 20 a b c "a", "b", "c" ``` -------------------------------- ### Moonscript: Copying a Table with Comprehension Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how to create a shallow copy of a table using a table comprehension. It iterates over key-value pairs of an existing table and constructs a new one, effectively duplicating its contents. ```moonscript thing = { color: "red" name: "fast" width: 123 } thing_copy = {k, v for k, v in pairs thing} ``` -------------------------------- ### Define and Call a Basic MoonScript Function Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates the fundamental syntax for defining an empty function using the '->' arrow and subsequently calling it. This illustrates the simplest form of function declaration in MoonScript. ```moonscript my_function = -> my_function() -- call the empty function ``` -------------------------------- ### Building YueScript Command-Line Executable Source: https://github.com/ippclub/yuescript/blob/main/CMakeLists.txt This CMake snippet defines and builds the main `yue` executable. It includes the core YueScript source files along with an additional `src/yue.cpp` for the executable's entry point, enabling it to be run as a standalone application. ```CMake add_executable(yue src/yuescript/ast.cpp src/yuescript/parser.cpp src/yuescript/yue_ast.cpp src/yuescript/yue_parser.cpp src/yuescript/yue_compiler.cpp src/yuescript/yuescript.cpp src/yue.cpp ) ``` -------------------------------- ### Moonscript: Array Slicing Omitting Maximum Bound Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how to use array slicing by omitting the maximum bound, which defaults to the length of the table. This example selects all items from the second element to the end of the `items` array. ```moonscript slice = [item for item in *items[2,]] ``` -------------------------------- ### Execute YueScript Code from File Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Loads YueScript code from a specified file and immediately executes it. This function is a convenience wrapper that combines loading and execution, returning the results of the executed code. It supports optional environment tables and compiler configurations. ```APIDOC dofile: function(filename: string, env: table, config?: Config): any... - Description: Loads YueScript code from a file into a function and executes it. - 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... - Description: Loads YueScript code from a file into a function and executes it. - Parameters: - filename: string - The file name. - config: Config - [Optional] The compiler options. - Returns: - any...: The return values of the loaded function. ``` -------------------------------- ### Create Table Keys from Variable Names with Colon Prefix in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how to use the colon prefix operator (:) to automatically create table keys that match the names of existing variables, providing a concise way to populate tables when keys and variable names are identical. ```moonscript hair = "golden" height = 200 person = { :hair, :height, shoe_size: 40 } print_table :hair, :height ``` -------------------------------- ### Demonstrating Destructive Assignment in MoonScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This MoonScript example illustrates a common issue where a local variable 'i' inside a function unintentionally overwrites a variable 'i' from the outer scope, leading to unexpected side effects. The outer 'i' is modified from 100 to 0. ```moonscript i = 100 -- many lines of code... my_func = -> i = 10 while i > 0 print i i -= 1 my_func! print i -- will print 0 ``` -------------------------------- ### Moonscript: Array Slicing with Negative Step for Reverse Order Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Explains how to use a negative step size in array slicing to iterate over items in reverse order. This example reverses the order of items from the last to the first in the `items` array. ```moonscript reverse_slice = [item for item in *items[-1,1,-1]] ``` -------------------------------- ### Define a simple class with constructor and method in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This snippet demonstrates how to define a basic class named `Inventory` in YueScript. It includes a constructor (`new`) to initialize instance-specific properties (like `@items`) and a method (`add_item`) to modify these properties. The use of fat arrow (`=>`) ensures `self` (represented by `@`) is correctly bound, and `@` is shorthand for `self.` access. ```moonscript class Inventory new: => @items = {} add_item: (name) => if @items[name] @items[name] += 1 else @items[name] = 1 ``` -------------------------------- ### Adding Platform-Specific efsw Sources and Definitions Source: https://github.com/ippclub/yuescript/blob/main/CMakeLists.txt This CMake section conditionally adds source files from the `efsw` (Event-driven File System Watcher) library based on the target operating system. It ensures that the correct platform-specific implementations for file system, mutex, and thread handling are included for Windows, macOS, Linux, and FreeBSD, and defines preprocessor macros as needed. ```CMake target_sources(yue PRIVATE src/3rdParty/efsw/Debug.cpp src/3rdParty/efsw/DirectorySnapshot.cpp src/3rdParty/efsw/DirectorySnapshotDiff.cpp src/3rdParty/efsw/DirWatcherGeneric.cpp src/3rdParty/efsw/FileInfo.cpp src/3rdParty/efsw/FileSystem.cpp src/3rdParty/efsw/FileWatcher.cpp src/3rdParty/efsw/FileWatcherCWrapper.cpp src/3rdParty/efsw/FileWatcherGeneric.cpp src/3rdParty/efsw/FileWatcherImpl.cpp src/3rdParty/efsw/Log.cpp src/3rdParty/efsw/Mutex.cpp src/3rdParty/efsw/String.cpp src/3rdParty/efsw/System.cpp src/3rdParty/efsw/Thread.cpp src/3rdParty/efsw/Watcher.cpp src/3rdParty/efsw/WatcherGeneric.cpp ) if (WIN32) target_sources(yue PRIVATE src/3rdParty/efsw/platform/win/FileSystemImpl.cpp src/3rdParty/efsw/platform/win/MutexImpl.cpp src/3rdParty/efsw/platform/win/SystemImpl.cpp src/3rdParty/efsw/platform/win/ThreadImpl.cpp ) else () target_sources(yue PRIVATE src/3rdParty/efsw/platform/posix/FileSystemImpl.cpp src/3rdParty/efsw/platform/posix/MutexImpl.cpp src/3rdParty/efsw/platform/posix/SystemImpl.cpp src/3rdParty/efsw/platform/posix/ThreadImpl.cpp ) endif() if (APPLE) target_sources(yue PRIVATE src/3rdParty/efsw/FileWatcherFSEvents.cpp src/3rdParty/efsw/FileWatcherKqueue.cpp src/3rdParty/efsw/WatcherFSEvents.cpp src/3rdParty/efsw/WatcherKqueue.cpp ) if (NOT CMAKE_SYSTEM_VERSION GREATER 9) target_compile_definitions(yue PRIVATE EFSW_FSEVENTS_NOT_SUPPORTED) endif() elseif (WIN32) target_sources(yue PRIVATE src/3rdParty/efsw/FileWatcherWin32.cpp src/3rdParty/efsw/WatcherWin32.cpp ) elseif (${CMAKE_SYSTEM_NAME} MATCHES "Linux") target_sources(yue PRIVATE src/3rdParty/efsw/FileWatcherInotify.cpp src/3rdParty/efsw/WatcherInotify.cpp ) if (NOT EXISTS "/usr/include/sys/inotify.h" AND NOT EXISTS "/usr/local/include/sys/inotify.h") target_compile_definitions(yue PRIVATE EFSW_INOTIFY_NOSYS) endif() elseif (${CMAKE_SYSTEM_NAME} MATCHES "FreeBSD") target_sources(yue PRIVATE src/3rdParty/efsw/FileWatcherKqueue.cpp src/3rdParty/efsw/WatcherKqueue.cpp ) endif() ``` -------------------------------- ### MoonScript Single-Line Switch When Clauses Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates the use of the 'then' keyword in MoonScript to write 'when' clauses on a single line, enhancing code brevity. This syntax provides a compact way to define actions for specific conditions within a switch statement. ```MoonScript msg = switch math.random(1, 5) when 1 then "you are lucky" when 2 then "you are almost lucky" else "not so lucky" ``` -------------------------------- ### Exporting and Importing Macros in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates how to define and export macros from one YueScript file (`utils.yue`) and then import and use them in another file (`main.yue`). It shows the syntax for exporting individual macros and importing all macros from a module, including renaming. ```MoonScript -- 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 _ ``` -------------------------------- ### Declaring Explicit Global Variables in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This example illustrates how to explicitly declare global variables in Moonscript using the `global` keyword. Similar to locals, it supports `global *` to declare all variables or `global ^` to declare only uppercase variables as globals within a block, controlling variable scope. ```moonscript do global a = 1 global * print "declare all variables as globals" x = -> 1 + y + z y, z = 2, 3 do global X = 1 global ^ print "only declare upper case variables as globals" a = 1 B = 2 local Temp = "a local value" ``` -------------------------------- ### Using `do` in Table Definitions in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Illustrates how a `do` expression can be used directly within a table definition to compute a key's value. This allows for multi-line initialization logic for a table field. ```moonscript tbl = { key: do print "assigning key!" 1234 } ``` -------------------------------- ### YueScript Library API (yue) Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Comprehensive API documentation for the 'yue' library, providing access to version information, platform-specific file separators, the compiled module code cache, and functions for compiling YueScript code to Lua, managing file system interactions, and integrating the YueScript loader into Lua's package system. ```APIDOC yue: -- Properties 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. -- Functions to_lua(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 Description: The YueScript code. config: Config Description: [Optional] The compiler options. Returns: string | nil Description: The compiled Lua code, or nil if the compilation failed. string | nil Description: The error message, or nil if the compilation succeeded. {{string, integer, integer}} | nil Description: The global variables appearing in the code (with name, row and column), or nil if the compiler option `lint_global` is false. file_exist(filename: string): boolean Description: The source file existence checking function. Can be overridden to customize the behavior. Parameters: filename: string Description: The file name. Returns: boolean Description: Whether the file exists. read_file(filename: string): string Description: The source file reading function. Can be overridden to customize the behavior. Parameters: filename: string Description: The file name. Returns: string Description: The file content. insert_loader(pos?: integer): boolean Description: Insert the YueScript loader to the package loaders (searchers). Parameters: pos: integer Description: [Optional] The position to insert the loader. Default is 3. Returns: boolean Description: Whether the loader is inserted successfully. It will fail if the loader is already inserted. ``` -------------------------------- ### Perform Basic List Comprehension in Moonscript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Introduces list comprehensions in Moonscript, showing how to transform elements of an existing table into a new array-like table using a `for` loop and an expression, similar to iterating with `ipairs`. ```moonscript items = [ 1, 2, 3, 4 ] doubled = [item * 2 for i, item in ipairs items] ``` -------------------------------- ### Concise Single-Line For Loop Syntax in YueScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows the abbreviated syntax for for loops when the loop body consists of a single statement, using the `do` keyword for brevity. ```moonscript for item in *items do print item for j = 1, 10, 3 do print j ``` -------------------------------- ### Selective Destructive Assignment with 'using' in MoonScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This MoonScript example shows how to selectively allow destructive assignment for specific variables from the enclosing scope using the 'using' keyword. Variables 'k' and 'i' are explicitly allowed to be modified, while 'tmp' creates a new local variable, demonstrating fine-grained control over scope modification. ```moonscript 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 ``` -------------------------------- ### Yuescript Array Element Pattern Matching Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Shows how to match against array elements in a `switch` statement. It covers exact array matching, matching with variable capture, and using default values for captured array elements, demonstrating flexibility in array pattern recognition. ```Moonscript 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}" ``` -------------------------------- ### Basic If-Else Conditional Block in MoonScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md Demonstrates the standard multi-line 'if-else' block for conditional execution, where different code paths are taken based on a boolean condition. ```moonscript have_coins = false if have_coins print "Got coins" else print "No coins" ``` -------------------------------- ### Preventing Destructive Assignment with 'using nil' in MoonScript Source: https://github.com/ippclub/yuescript/blob/main/doc/docs/doc/README.md This MoonScript example demonstrates how the 'using nil' clause prevents a function from accidentally overwriting variables from its enclosing scope. When 'i = "hello"' is executed, a new local variable 'i' is created instead of modifying the outer 'i', preserving its original value of 100. ```moonscript i = 100 my_func = (using nil) -> i = "hello" -- a new local variable is created here my_func! print i -- prints 100, i is unaffected ```