### wxLua wxGrid Sample using wxm Source: https://github.com/leafo/moonscript/wiki/Wxlua Demonstrates creating a wxLua application with a wxGrid using the wxm helper module. This example shows frame creation, menu setup, toolbar, status bar, and grid cell manipulation. Requires the wxm module. ```moonscript wxm = require 'wxm' frame = wxm.frame "wxLua wxGrid Sample",{},{350,250} ids = EXIT: wxm.ID_EXIT, ABOUT:wxm.ID_ABOUT import menu from wxm menu.bar { menu "&File", { menu.item -1, "&Open", -> print 'opening sesame' menu.item ids.EXIT, "E&xit\tCtrl-X", "Quit the program",-> frame\Close! } menu "&Help", { menu.item ids.ABOUT, "&About\tCtrl-A", "About the Grid wxLua Application",-> wxm.MessageBox "Simplified wx with Moon", "About wxLua", wxm.OK + wxm.ICON_INFORMATION, frame } } wxm.toolbar nil, { {ids.EXIT, 'Exit', 'ERROR'} {-1,'-'} {ids.ABOUT, 'About', 'HELP'} } frame\CreateStatusBar 1 frame\SetStatusText "Welcome to wxLua." grid = wxm.Grid frame, wxm.ID_ANY grid\CreateGrid 10, 8 grid\SetColSize 3, 200 grid\SetRowSize 4, 45 grid\SetCellValue 0, 0, "First cell" grid\SetCellValue 1, 1, "Another cell" grid\SetCellValue 2, 2, "Yet another cell" grid\SetCellFont 0, 0, wxm.Font 10, wxm.ROMAN, wxm.ITALIC, wxm.NORMAL grid\SetCellTextColour 1, 1, wxm.RED grid\SetCellBackgroundColour 2, 2, wxm.CYAN wxm.go! ``` -------------------------------- ### Sequence Computation Example in Moonscript Source: https://github.com/leafo/moonscript/wiki/Monads-in-Moonscript An example demonstrating the use of the `sequence` helper to perform multiple stack operations and combine their results, showcasing a more streamlined approach to chained computations. ```moonscript c2 = sequence { push(4) push(5) pop! pop! (r1,r2) -> result r1..' : '..r2 } print evalStack c2, {} ``` -------------------------------- ### wxm.go Source: https://github.com/leafo/moonscript/wiki/Wxlua Shows the main frame and starts the wxWidgets application's main event loop. ```APIDOC ## wxm.go ### Description Displays the main frame and enters the application's main event loop. ### Usage Call this function after setting up all UI elements to run the application. ``` -------------------------------- ### MoonScript Flags Parser Usage Example Source: https://github.com/leafo/moonscript/wiki/Flags-Parser This example demonstrates how to use the flags parser with a sample usage string and arguments. It requires the 'flags' module and 'moondump' for pretty printing the results. The output shows parsed arguments, including flags that take values and boolean flags. ```moonscript flags = require 'flags' tstring = require 'moondump' usage = [[ usage: lglob [options] -t means "tolerant"; defined globals are ok (implies -g and -l) -g accept globals defined in a module -l call require() to track module exports -w , whitelist file containing symbol={entries..}, which are added to _G. ]] args = flags.parse usage dump = (t) -> print tstring t dump args ``` -------------------------------- ### MoonScript List Comprehension Example Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Provides an example of a list comprehension, which creates a new list by transforming elements from an existing list. ```moonscript -- Creates a copy of a list but with all items doubled. Using a star before a ``` -------------------------------- ### Binary Counting Example Source: https://github.com/leafo/moonscript/wiki/permutations A practical example of using permutations to count in binary up to 2^n - 1. It reads 'n' from input and prints binary representations. ```moonscript -- count in binary print "--- Count to 2^n - 1 in binary ---" io.write "n: " bits = io.read! print "--- Counting up to #{2^bits - 1}, or #{'1'} ep bits ---" for permutation in permutations unpack (for i = 1, bits do {1, 0}) print table.concat permutation ``` -------------------------------- ### MoonScript File for Code Coverage Example Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md A simple MoonScript file used to demonstrate the code coverage feature of the `moon -c` command. ```moon -- test.moon first = -> print "hello" second = -> print "world" first! ``` -------------------------------- ### Moonscript Module Writing Example Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Demonstrates the recommended way to write modules in Moonscript by returning a table. This approach is compatible with Lua 5.2's module system. ```moonscript MY_CONSTANT = "hello" my_function = -> print "the function" my_second_function = -> print "another function" { :my_function, :my_second_function, :MY_CONSTANT} ``` -------------------------------- ### Get Help for `moon` Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Use the `-h` or `--help` flag to display a full list of available options for the `moon` command. ```bash $ moon -h ``` -------------------------------- ### Equivalent Nested Loops Source: https://github.com/leafo/moonscript/wiki/permutations Shows the equivalent nested for loop structure for the basic permutations usage example. ```moonscript for i = 1, 3 for j = 1, 3 for k = 1, 3 print i, j, k ``` -------------------------------- ### MoonScript Assignment Examples Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates various assignment operators in MoonScript, including direct assignment, augmented assignment (+=, ..=, and=), and overwriting variables. ```moonscript hello = "world" a, b, c = 1, 2, 3 hello = 123 -- Overwrites `hello` from above. x = 0 x += 10 -- x = x + 10 s = "hello " s ..= "world" -- s = s .. "world" b = false b and= true or false -- b = b and (true or false) ``` -------------------------------- ### Example usage of is_instance method in Moonscript Source: https://github.com/leafo/moonscript/wiki/Object-and-class-inspection-functions Demonstrates calling `is_instance` as a method on classes to check for instances or subclasses. Shows expected outputs for various scenarios. ```moonscript class Foo :is_instance class Bar extends Foo class Baz extends Bar Bar\is_instance Foo --> false Bar\is_instance Foo! --> false Bar\is_instance Bar --> Bar Bar\is_instance Bar! --> Bar Bar\is_instance Baz --> Baz Bar\is_instance Baz! --> Baz Bar\is_instance 'Bar' --> nil ``` -------------------------------- ### Get Help for `moonc` Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Use the `-h` or `--help` flag to display a full list of available options for the `moonc` command. ```bash $ moonc -h ``` -------------------------------- ### Moonscript Function Stub Example Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Demonstrates how to use function stub syntax to bundle an object with its method for use as a callback. This ensures the method is called with the correct object context. ```moonscript my_object = { value: 1000 write: => print "the value:", @value } run_callback = (func) -> print "running callback..." func! -- this will not work: -- the function has to no reference to my_object run_callback my_object.write -- function stub syntax -- lets us bundle the object into a new function run_callback my_object\write ``` -------------------------------- ### Example Usage of Immutable Fields Source: https://github.com/leafo/moonscript/wiki/Immutable-object-fields Demonstrates how to define a class with an immutable field 'foo' and shows the expected behavior when attempting to modify it after instantiation. ```moonscript class MyClass const self, 'foo' new: (@foo)=> bar: => print "foo is #{@foo}" with MyClass 'baz' \bar! --> foo is baz .foo = "biz" --> error: attempt to modify immutable field 'foo' of MyClass. ``` -------------------------------- ### Example of flattening a nested table Source: https://github.com/leafo/moonscript/wiki/Table-flattening Demonstrates the input and output of the `flatten` function when applied to a deeply nested table. ```moonscript flatten { 1 2 { { 3 4 } 5 } { { 6 } { { 7 } } } } ``` ```moonscript { 1 2 3 4 5 6 7 } ``` -------------------------------- ### Example of flattening all sequences recursively Source: https://github.com/leafo/moonscript/wiki/Table-flattening Demonstrates `flatten_all_sequences` on a nested table, showing that sequence sub-tables within non-sequence tables are also flattened. ```moonscript flatten_all_sequences { 1 {2} { a: 'b' c: 'd' { 3 {4} } } { 5 {6} } } ``` ```moonscript { 1 2 { a: 'b' c: 'd' { 3 4 } } 5 6 } ``` -------------------------------- ### Monadic Computation Example in Moonscript Source: https://github.com/leafo/moonscript/wiki/Monads-in-Moonscript Demonstrates a monadic computation using `bind`, `push`, `pop`, and `result` to perform a sequence of stack operations and combine their results. ```moonscript computation = bind push(4),-> bind push(5), -> bind pop(), (r1) -> bind pop(), (r2) -> result r1..' : '..r2 print evalStack computation, {} -- "5 : 4" ``` -------------------------------- ### Writing Modules in MoonScript Source: https://context7.com/leafo/moonscript/llms.txt MoonScript files implicitly return their last expression, simplifying module definitions. This example shows how to define and export functions and constants from a module. ```moonscript -- math_utils.moon local * -- forward-declare all names PI = 3.14159265358979 -- private helper _deg_to_rad = (deg) -> deg * PI / 180 circle_area = (r) -> PI * r * r circle_perimeter = (r) -> 2 * PI * r rotate = (x, y, deg) -> rad = _deg_to_rad deg c, s = math.cos(rad), math.sin(rad) x * c - y * s, x * s + y * c -- return the public API (implicit return) { :PI, :circle_area, :circle_perimeter, :rotate } ``` ```moonscript -- main.moon require "moonscript" -- install loader mu = require "math_utils" print mu.PI -- 3.14159265358979 print mu.circle_area 5 -- 78.539816339745 x2, y2 = mu.rotate 1, 0, 90 print x2, y2 -- ~0 1 ``` -------------------------------- ### Run wxWidgets Application Main Loop in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Shows the main frame and starts the wxWidgets application's main event loop. This function should typically be called last. ```lua wxm.go = -> _frame\Show true wxm.GetApp!\MainLoop! ``` -------------------------------- ### Run MoonScript Tests Source: https://github.com/leafo/moonscript/blob/master/README.md Execute tests using Busted. Requires MoonScript and Loadkit to be installed. ```bash busted ``` -------------------------------- ### Example of flattening a table with non-integer keys Source: https://github.com/leafo/moonscript/wiki/Table-flattening Illustrates how the `flatten` function handles tables containing non-integer keys, showing that these keys and their associated values are ignored in the flattened output. ```moonscript flatten { 1 {2} { a: 'b' c: 'd' { 3 {4} } } { 5 {6} } } ``` ```moonscript { 1 2 3 4 5 6 } ``` -------------------------------- ### Example of flattening only direct sequences Source: https://github.com/leafo/moonscript/wiki/Table-flattening Shows the output of `flatten_direct_sequences` on a mixed table, demonstrating that only the top-level sequence is flattened, while nested non-sequence tables remain intact. ```moonscript flatten_direct_sequences { 1 {2} { a: 'b' c: 'd' { 3 {4} } } { 5 {6} } } ``` ```moonscript { 1 2 { a: 'b' c: 'd' { 3 {4} } } 5 6 } ``` -------------------------------- ### Export All and Export Proper in MoonScript Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md MoonScript provides `export *` to export all subsequent names and `export ^` to export only names starting with a capital letter. ```moonscript export * export ^ ``` -------------------------------- ### MoonScript Slicing with Step Size Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Specify a step size in slicing to select elements at intervals. Omitting bounds defaults them to the start and end of the table. ```moon slice = [item for item in *items[,,2]] ``` -------------------------------- ### MoonScript Slicing with Max Bound Omitted Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md When the maximum bound is omitted in slicing, it defaults to the length of the table. This example takes all elements starting from the second. ```moon slice = [item for item in *items[2,]] ``` -------------------------------- ### Get Class-Aware Type Source: https://github.com/leafo/moonscript/blob/master/docs/standard_lib.md Use `type` to get the class of an instance, the string 'class' for a class table, or the Lua built-in type for other values. ```moon class MyClass x = MyClass! assert type(x) == MyClass assert type(MyClass) == "class" assert type(MyClass.__base) == "table" ``` -------------------------------- ### Run All Tests with Make Source: https://github.com/leafo/moonscript/blob/master/spec/README.md Conveniently run all tests, including setting up the development environment, using the provided make task. ```bash make test ``` -------------------------------- ### wxLua wxTreeCtrl Sample Source: https://github.com/leafo/moonscript/wiki/Wxlua Demonstrates creating a wxLua application with a wxTreeCtrl and a log window. It includes event handling for tree item interactions and menu actions. Requires the wxLua environment. ```moonscript -- tree.wx.moon require "wx" -- create a table to store any extra information for each node like this -- you don't have to store the id in the table, but it might be useful -- treedata[id] = { id=wx.wxTreeCtrlId, data="whatever data we want" } treedata = {} treedata.put = (id,str) -> val = id\GetValue! treedata[val] = id:val, data:str any = wx.wxID_ANY defpos = wx.wxDefaultPosition defsize = wx.wxDefaultSize main = -> frame = wx.wxFrame wx.NULL, any, "wxLua wxTreeCtrl Sample", defpos, wx.wxSize(600, 400), wx.wxDEFAULT_FRAME_STYLE -- create the menubar and attach it fileMenu = wx.wxMenu! fileMenu\Append wx.wxID_EXIT, "E&xit", "Quit the program" helpMenu = wx.wxMenu! helpMenu\Append wx.wxID_ABOUT, "&About", "About the wxLua wxTreeCtrl Sample" menuBar = wx.wxMenuBar! menuBar\Append fileMenu, "&File" menuBar\Append helpMenu, "&Help" frame\SetMenuBar menuBar frame\Connect wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,-> frame\Close true frame\Connect wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,-> wx.wxMessageBox 'This is the "About" dialog of the wxLua wxTreeCtrl sample.\n'..wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING, "About wxLua", wx.wxOK + wx.wxICON_INFORMATION, frame splitter = wx.wxSplitterWindow frame,any,defpos,defsize -- create our treectrl tree = wx.wxTreeCtrl splitter, any, defpos, defsize, wx.wxTR_LINES_AT_ROOT + wx.wxTR_HAS_BUTTONS -- create our log window textCtrl = wx.wxTextCtrl splitter, any, "", defpos, defsize, wx.wxTE_READONLY + wx.wxTE_MULTILINE splitter\SetMinimumPaneSize 50 splitter\SplitVertically tree, textCtrl, 200 root_id = tree\AddRoot "Root" treedata.put root_id, "I'm the root item" for idx = 0, 10 parent_id = tree\AppendItem root_id, "Parent (#{idx})" treedata.put parent_id, "I'm the data for Parent (#{idx})" for jdx = 0, 5 child_id = tree\AppendItem parent_id, "Child (#{idx},#{jdx})" treedata.put child_id, "I'm the child data for Parent (#{idx},#{jdx}))" if idx == 2 or idx == 5 tree\Expand parent_id tree_event = (evnt,name) -> tree\Connect evnt,(event) -> value = event\GetItem!\GetValue! textCtrl\AppendText "Item #{name}: #{tostring(value)} '#{treedata[value].data}'\n" -- connect to some events from the wxTreeCtrl tree_event wx.wxEVT_COMMAND_TREE_ITEM_EXPANDING,"expanding" tree_event wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSING, "collapsing" tree_event wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED, "activated" tree_event wx.wxEVT_COMMAND_TREE_SEL_CHANGED, "sel changed" tree\Expand root_id frame\Show true main! wx.wxGetApp!\MainLoop! ``` -------------------------------- ### Mooni REPL Command-line Options Source: https://github.com/leafo/moonscript/wiki/Moonscriptrepl Shows how to use the 'mooni' REPL with command-line flags for loading libraries and evaluating expressions directly. ```bash scratch$ mooni -llfs -e 'lfs.currentdir!' /home/steve/moonscript/scratch ``` -------------------------------- ### MoonScript Table Construction from Variables Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Illustrates the shorthand syntax for creating table fields when the key name is the same as the variable name, using a colon prefix. ```moonscript hair = "golden" height = 200 person = {:hair, :height} ``` -------------------------------- ### MoonScript Comment Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Single-line comments start with '--' and are ignored during compilation. ```moonscript -- I am a comment ``` -------------------------------- ### MoonScript Numeric For Loop Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Standard numeric for loop iterating from a start to an end value. ```moon for i = 10, 20 print i ``` -------------------------------- ### wxm.toolbar Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a toolbar for the main frame with specified style and items. ```APIDOC ## wxm.toolbar ### Description Creates and configures a toolbar for the main frame. ### Parameters - **style** (number, optional) - The style flags for the toolbar. Defaults to `wxm.NO_BORDER + wxm.TB_FLAT + wxm.TB_DOCKABLE`. - **items** (table) - A list of items to add to the toolbar. Each item is a table containing id, text, bitmap, and optional hint string. ### Returns - wx.ToolBar - The created toolbar object. ``` -------------------------------- ### wxm.nextID Source: https://github.com/leafo/moonscript/wiki/Wxlua Generates the next available menu or toolbar item ID, starting from `wxm.ID_HIGHEST`. ```APIDOC ## wxm.nextID ### Description Generates a unique ID for menu items or toolbar buttons. ### Returns - number - The next available ID. ``` -------------------------------- ### wxm.menu.bar Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a menu bar and appends menus to it. The menu bar is then set on the main frame. ```APIDOC ## wxm.menu.bar ### Description Creates a menu bar and adds menus to it. ### Parameters - **items** (table) - A list of menus to add to the menu bar. Each item is expected to be a table containing menu data. ### Returns - wx.MenuBar - The created menu bar object. ``` -------------------------------- ### wxm.menu.dropdown Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a dropdown menu with a specified text label and a list of menu items. ```APIDOC ## wxm.menu.dropdown ### Description Creates a dropdown menu. ### Parameters - **text** (string) - The text label for the menu. - **items** (table) - A list of menu items. Each item is expected to be a table that can be unpacked into `menu:Append`. ### Returns - table - A table containing the menu object and its text label. ``` -------------------------------- ### debug.upvalue(fn, key[, value]) Source: https://github.com/leafo/moonscript/blob/master/docs/standard_lib.md Gets or sets the value of an upvalue for a given function by its name. This is primarily for debugging purposes. ```APIDOC ## debug.upvalue(fn, key[, value]) ### Description Gets or sets the value of an upvalue for a function by name. ``` -------------------------------- ### Moonscript Operator Ambiguity Examples Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Illustrates how whitespace affects the interpretation of the minus sign as a unary negation or binary subtraction operator. ```moonscript a = x - 10 b = x-10 c = x -y d = x- z ``` -------------------------------- ### Create wxWidgets Toolbar in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a toolbar for the frame with specified styles and items. It handles bitmap loading from strings and adds separators or tools. The toolbar is realized after adding all items. ```lua wxm.toolbar = (style,items) -> style = style or wxm.NO_BORDER + wxm.TB_FLAT + wxm.TB_DOCKABLE tbar = _frame\CreateToolBar style for item in *items id, text, bm, hintstr = item[1], item[2], item[3], item[4] if type(bm) == 'string' then bm = wxm.bitmap bm if id == -1 and text == '-' tbar\AddSeparator! else tbar\AddTool id, text, bm, hintstr or text tbar\Realize! ``` -------------------------------- ### MoonScript Class Instance Creation Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Create an instance of a class by calling its name as a function. Use the `\` operator to pass the instance as the first argument to methods. ```moonscript inv = Inventory! inv\add_item "t-shirt" inv\add_item "pants" ``` -------------------------------- ### Basic try/catch with pcall in MoonScript Source: https://github.com/leafo/moonscript/wiki/Exception-handling Demonstrates a basic `try/catch` structure using Lua's `pcall` in MoonScript. Errors are caught and a cleaned-up error message is printed. ```moonscript try = (f) -> ok,err = pcall f if not ok then err\gsub '^[^:]+:%d+: ','' err = try -> print a.x if err print 'error!',err ``` -------------------------------- ### MoonScript Class Expressions Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md MoonScript supports class expressions that can be assigned to variables or returned. This example shows a simple class with a property and a method. ```moonscript x = class Bucket drops: 0 add_drop: => @drops += 1 ``` -------------------------------- ### MoonScript Implicit Return Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md The last statement in a function body is implicitly returned. This example shows a function returning the sum of two numbers. ```moonscript sum = (x, y) -> x + y print "The sum is ", sum 10, 20 ``` -------------------------------- ### MoonScript Table Keys and Indexing Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates how to use non-string or non-numeric keys in tables using square brackets `[]` and shows that string literals can be used directly as keys without brackets. ```moonscript t = [1 + 2]: "hello" "hello world": true ``` -------------------------------- ### Slicing in For Loops and Comprehensions Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Iterate over a specific range of an array using slicing syntax `[start, end, step]`. The step and end are optional. ```moonscript for item in *points[1, 10, 2] print unpack item ``` ```moonscript words = {"these", "are", "some", "words"} for word in *words[,3] print word ``` -------------------------------- ### Using 'with' as an Expression in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates that 'with' can be used as an expression, allowing assignments within it to be used immediately, as shown with the string manipulation example. ```moonscript with str = "Hello" -- assignment as expression! :D print "original: #{str}" print "upper: #{\upper!}" ``` -------------------------------- ### Basic Destructuring Assignment Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Extracts values from a table into local variables by matching keys or positions. This example unpacks the first two values from an array-like table. ```moonscript thing = {1,2} {a,b} = thing print a,b ``` -------------------------------- ### Moonscript Code with Unused Variable Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Example Moonscript code that includes an unused variable assignment. The linter will report this as an issue, helping to keep the code clean. ```moononly a, b = 1, 2 print "hello", a ``` -------------------------------- ### For Loop Returning `nil` vs. Table Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates how a `for` loop as the last statement in a function returns `nil`, while an explicit `return` generates a table. ```moonscript print_squared = (t) -> for x in *t do x*x -- returns `nil` squared = (t) -> return for x in *t do x*x -- returns new table of squares ``` -------------------------------- ### Importing Functions and Values in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates importing specific functions or values from tables using 'import' and 'from'. It shows importing a function from 'table' and a custom function with state from a literal table. ```moonscript -- Values from a table can be brought to the current scope using the `import` -- and `from` keyword. Names in the `import` list can be preceded by `\` if -- they are a module function. import insert from table -- local insert = table.insert import \add from state: 100, add: (value)=> @state + value print add 22 -- Like tables, commas can be excluded from `import` lists to allow for longer -- lists of imported items. import asdf, gh, jkl antidisestablishmentarianism from {} ``` -------------------------------- ### Compile Linter Configuration File Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Compile the `lint_config.moon` file using `moonc`. This step is necessary before the linter can use the custom configuration. ```bash $ moonc lint_config.moon ``` -------------------------------- ### Create wxWidgets Menu Bar in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Constructs a menu bar and appends menus to it. Each item in the `items` table should contain the menu object and its title. ```lua wxm.menu.bar = (items) -> mbar = wxm.MenuBar! for item in *items mbar\Append item[1], item[2] _frame\SetMenuBar mbar ``` -------------------------------- ### Create wxWidgets Menu Item in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a menu item, handling optional hint strings and callbacks. If an ID is -1, it generates a new ID using `wxm.nextID()`. Connects the item's ID to a callback function for command events. ```lua wxm.menu.item = (id,text,hintstr,callback) -> if type(hintstr) == 'function' then callback = hintstr if not hinstr then hintstr = '' if id == -1 then id = wxm.nextID! if callback _frame\Connect id, wxm.EVT_COMMAND_MENU_SELECTED, callback {id,text,hintstr} ``` -------------------------------- ### Anonymous Classes in MoonScript Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Classes can be declared anonymously by omitting the name. The `__name` attribute will be `nil` unless assigned. This example demonstrates extending a base class anonymously. ```moonscript BigBucket = class extends Bucket add_drop: => @drops += 10 assert Bucket.__name == "BigBucket" ``` ```moonscript x = class ``` -------------------------------- ### Loading and Compiling MoonScript with `moonscript.base` Source: https://github.com/leafo/moonscript/blob/master/docs/api.md The `moonscript.base` module provides functions analogous to Lua's `load`, `loadfile`, and `loadstring` for handling MoonScript code. ```APIDOC ## `moonscript.base` Module ```moononly moonscript = require "moonscript.base" ``` This module contains an assortment of functions for loading and compiling MoonScript code from within Lua. The module provides `load`, `loadfile`, `loadstring` functions, which are anologous to the similarly named Lua functions. The major difference is that they load MoonScript code instead of Lua code. ```moononly moonscript = require "moonscript.base" fn = moonscript.loadstring 'print "hi!"' fn! ``` All of these functions can take an optional last argument, a table of options. The only option right now is `implicitly_return_root`. Setting this to `false` makes it so the file does not implicitly return its last statement. ```moononly moonscript = require "moonscript.base" fn = moonscript.loadstring "10" print fn! -- prints "10" fn = moonscript.loadstring "10", implicitly_return_root: false print fn! -- prints nothing ``` One more useful function is provided: `to_lua`. This function takes a string of MoonScript code and returns the compiled Lua result along with the line mapping table. If there are any errors then `nil` and the error message are returned. ```moononly import to_lua from require "moonscript.base" lua_code, line_table = to_lua [[ x = 124 print "hello world #{x}" ]] ``` Similar to the `load*` functions from above, `to_lua` can take an optional final argument of a table of options. The second return value of `to_lua` is useful if you want to perform line number reversal. It's a table where the key is a Lua line number and the value is a character offset from the original MoonScript source. ``` -------------------------------- ### Create wxWidgets Dropdown Menu in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Creates a dropdown menu with a tearoff option. It iterates through provided items and appends them to the menu. Returns the menu object and its text. ```lua wxm.menu = {} wxm.menu.dropdown = (text,items) -> menu = wxm.Menu "", wxm.MENU_TEAROFF for item in *items menu\Append unpack item {menu, text} ``` -------------------------------- ### MoonScript Code with Runtime Error Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Example of a MoonScript file containing a bug that will trigger a runtime error. The error message demonstrates MoonScript's error rewriting. ```moon add_numbers = (x,y) -> x + z -- 1 print add_numbers 10,0 -- 2 ``` -------------------------------- ### Example Usage of Lock Immutable Field Source: https://github.com/leafo/moonscript/wiki/Immutable-object-fields Illustrates how to use `lock_const` within a class constructor to ensure a field remains immutable, especially when passing `self` to other functions. ```moonscript class MyClass const self, 'foo' new: (@foo)=> lock_const self, 'foo' untrusted_function self ``` -------------------------------- ### Build Syntax Test Outputs Source: https://github.com/leafo/moonscript/blob/master/spec/README.md Rebuild expected outputs for syntax tests by running the syntax test suite with the `BUILD` environment variable set. A make task is available for convenience. ```bash make build_test_outputs ``` -------------------------------- ### Creating Scopes with 'do' in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Illustrates using 'do' to create a new local scope for variables. It can also be used as an expression to create closures, as shown with the 'counter' example. ```moonscript -- `do` lets you manually create a scope, for when you need local variables. do x = 5 print x -- nil -- Here we use `do` as an expression to create a closure. counter = do i = 0 -> i += 1 return i print counter! -- 1 print counter! -- 2 ``` -------------------------------- ### Basic Permutations Usage Source: https://github.com/leafo/moonscript/wiki/permutations Demonstrates a simple use case of the permutations iterator with a 3x3x3 range. ```moonscript for permutation in permutations 3, 3, 3 print unpack permutation ``` -------------------------------- ### Moon Linter Configuration Source: https://context7.com/leafo/moonscript/llms.txt Configure the `moonc` linter by creating a `lint_config.moon` file to whitelist globals per path pattern and suppress false positives. Compile the config using `moonc lint_config.moon` and lint the project with `moonc --lint .`. ```moonscript -- lint_config.moon { whitelist_globals: -- Allow Busted test globals in spec/ files ["spec/"]: { "it", "describe", "context", "setup", "teardown", "before_each", "after_each", "pending", "spy", "stub", "mock" }, -- Allow custom framework globals project-wide [""]: { "app", "config", "log" } } ``` ```bash # Compile the config moonc lint_config.moon # Lint the whole project using the config moonc --lint . # Expected output when a bug is found: # ./src/game.moon # line 12: accessing global `playre` <- typo caught! # ===================================== # > playre\move 1, 0 ``` -------------------------------- ### bind_methods(obj) Source: https://github.com/leafo/moonscript/blob/master/docs/standard_lib.md Takes an instance of an object and returns a proxy to that object. Methods called on the proxy will not require `self` as the first argument, as it's implicitly handled. ```APIDOC ## bind_methods(obj) ### Description Takes an instance of an object, returns a proxy to the object whose methods can be called without providing self as the first argument. ### Example ```moon obj = SomeClass! bound_obj = bind_methods obj -- following have the same effect obj\hello! bound_obj.hello! ``` It lazily creates and stores in the proxy table the bound methods when they are first called. ``` -------------------------------- ### Generate Next Available ID in Lua Source: https://github.com/leafo/moonscript/wiki/Wxlua Provides a function to generate unique IDs for menu items or other wxWidgets elements. It initializes a counter if not already set, starting from `wxm.ID_HIGHEST`. ```lua id_counter = nil wxm.nextID = -> if not id_counter then id_counter = wxm.ID_HIGHEST id_counter += 1 return id_counter ``` -------------------------------- ### Interactive MoonScript REPL Session Source: https://github.com/leafo/moonscript/wiki/Moonscriptrepl Demonstrates a typical interactive session with the MoonScript REPL, showcasing variable assignment, list comprehensions, function definition, and multi-line block execution using a trailing backslash. ```moonscript scratch$ mooni MoonScript version 0.2.3 Note: use backslash or tab to start a block > i = 1 > i 1 > [x for x = 1,5] {1,2,3,4,5} > #_ 5 > S = (x) -> x*x > [S x for x = 1,10] {1,4,9,16,25,36,49,64,81,100} > for i = 1,5 \ >> print 'hello', i >> hello 1 hello 2 hello 3 hello 4 hello 5 ``` -------------------------------- ### Auto-compile MoonScript on `require` Source: https://context7.com/leafo/moonscript/llms.txt The `moonscript` module installs a custom Lua package loader. This allows `require` calls to transparently load `.moon` files by compiling them in memory on demand. ```lua -- In a Lua entry point: require "moonscript" -- From this point on, requiring a .moon module works transparently: local my_mod = require "my_module" -- loads my_module.moon if found local other = require "utils.math" -- loads utils/math.moon ``` -------------------------------- ### Forward Declaration with Local in MoonScript Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md MoonScript offers `local *` to forward declare all subsequent names and `local ^` for names starting with a capital letter, useful for handling mutual recursion or dependencies. ```moonscript local first, second first = -> second! second = -> first! ``` ```moonscript local * first = -> print data second! second = -> first! data = {} ``` -------------------------------- ### Exporting Classes and All Values in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates exporting entire classes using 'export' and using 'export ^' to automatically export all CamelCase variables, or 'export *' to export all values. ```moonscript -- Classes can also be prefixed with `export` to make them global classes. -- Alternatively, all CamelCase variables can be exported automatically using -- `export ^`, and all values can be exported using `export *`. ``` -------------------------------- ### Simple try/catch/finally implementation in MoonScript Source: https://github.com/leafo/moonscript/wiki/Exception-handling A straightforward implementation of `try`, `catch`, and `finally` using `pcall`. This version may skip `finally` if `catch` itself throws an error. ```moonscript try = (t) -> ok,err = pcall t.do if not ok t.catch err t.finally! if t.finally ``` -------------------------------- ### Set Lua Module Paths on Windows Source: https://github.com/leafo/moonscript/wiki/Windows-issues On Windows, set LUA_PATH and LUA_CPATH environment variables to include directories where Lua modules and C libraries are installed. This ensures Moonscript can locate them. ```shell set LUA_PATH=;;d:\utils\lua\lua\?.lua;d:\utils\lua\lua\?\init.lua set LUA_CPATH=;;d:\utils\lua\clibs\?.dll ``` -------------------------------- ### Autocompiling with the `moonscript` Module Source: https://github.com/leafo/moonscript/blob/master/docs/api.md Include the `moonscript` module to enable automatic compilation of `.moon` files when using `require`. ```APIDOC ## Autocompiling with the `moonscript` Module After installing MoonScript, you can include the `moonscript` module to make any Lua script MoonScript aware. ```lua require "moonscript" ``` After `moonscript` is required, Lua's package loader is updated to search for `.moon` files on any subsequent calls to `require`. The search path for `.moon` files is based on the current `package.path` value in Lua when `moonscript` is required. Any search paths in `package.path` ending in `.lua` are copied, rewritten to end in `.moon`, and then inserted in `package.moonpath`. The `moonloader` is the function that is responsible for searching `package.moonpath` for a file available to be included. It is inserted in the second position of the `package.loaders` table. This means that a matching `.moon` file will be loaded over a matching `.lua` file that has the same base name. For more information on Lua's `package.loaders` see [Lua Reference Manual — package.loaders](http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders) The `moonloader`, when finding a valid path to a `.moon` file, will parse and compile the file in memory. The code is then turned into a function using the built in `load` function, which is run as the module. If you are executing MoonScript code with the included `moon` command line tool then it is not required to include this module before including any other MoonScript modules. ``` -------------------------------- ### Moonscript Code with Global Variable Typo Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Example Moonscript code containing a typo in a global variable access, which the linter can detect. This code demonstrates a scenario where a bug might be missed during development. ```moononly -- lint_example.moon my_number = 1234 some_function = -> -- a contrived example with a small chance to pass if math.random() < 0.01 my_nmuber + 10 some_function! ``` -------------------------------- ### Moonscript implementation to flatten only direct sequences Source: https://github.com/leafo/moonscript/wiki/Table-flattening Implements `flatten_direct_sequences`, which flattens tables only if they are considered 'direct sequences' (i.e., have contiguous integer keys starting from 1). Non-sequence tables and their contents are preserved. ```moonscript _insert_many = (...)=> for val in *{...} do self[#self + 1] = val fold = nil do _fold = (fn, a, b, ...)-> if b then _fold fn, fn(a, b), ... else a fold = (fn)=> _fold fn, unpack self _flatten_direct_sequences = => switch type self when 'table' if #self == moon.fold [1 for k in pairs self], (a, b)-> a + b result = {} for v in *self do _insert_many result, _flatten v unpack result else self else self export flatten_direct_sequences = (...)-> {_flatten_direct_sequences ...} ``` -------------------------------- ### Require MoonScript Standard Library Source: https://github.com/leafo/moonscript/blob/master/docs/standard_lib.md Import the entire standard library into the 'moon' object. Use 'moon.p' for debugging. ```moon moon = require "moon" -- `moon.p` is the debug printer moon.p { hello: "world" } ``` -------------------------------- ### Lint Entire Project Directory Source: https://github.com/leafo/moonscript/blob/master/docs/command_line.md Run the Moonscript linter on the entire project directory (`.`). This command will apply the configured global variable whitelist to all `.moon` files. ```bash $ moonc -l . ``` -------------------------------- ### Table Comprehension for Key-Value Pairs Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Create a copy of a table by iterating over its key-value pairs using `pairs`. ```moonscript thing = color: "red", name: "thing", width: 123 thing_copy = {k, v for k, v in pairs thing} ``` -------------------------------- ### MoonScript Function Literals with Arguments Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates defining functions that accept arguments. The last expression in a function body is implicitly returned. ```moonscript sum = (x, y)-> x + y -- The last expression is returned from the function. print sum(5, 10) ``` -------------------------------- ### Define and Use a Class with Methods in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Defines a class 'Inventory' with a method 'add_item' that initializes and increments item counts. Instances are created by calling the class, and methods are accessed using the '\' operator. ```moonscript class Inventory new: (items) => @items = items or {} add_item: (name)=> @items[name] = 0 unless @items[name] @items[name] += 1 -- Creating an instance of the class is as simple as calling the class as a -- function. Calling functions inside of the class uses \ to separate the -- instance from the function it is calling. inv = Inventory! inv\add_item "t-shirt" inv\add_item "pants" ``` -------------------------------- ### wxm.bitmap Source: https://github.com/leafo/moonscript/wiki/Wxlua Retrieves a wxWidgets bitmap from the ArtProvider. The kind defaults to 'MENU'. ```APIDOC ## wxm.bitmap ### Description Gets a bitmap from the wx.ArtProvider. ### Parameters - **name** (string) - The name of the bitmap to retrieve (e.g., 'wxART_FOLDER'). - **kind** (string, optional) - The kind of bitmap (e.g., 'MENU', 'TOOLBAR'). Defaults to 'MENU'. ### Returns - wx.Bitmap - The requested bitmap object. ``` -------------------------------- ### MoonScript Multi-line Function Arguments Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Demonstrates how function arguments can span multiple lines if indented, allowing for complex or lengthy argument lists. ```moonscript my_func 5, 8, another_func 6, 7, 9, 1, 2, 5, 4 if func 1, 2, 3, "hello", "world" print "hello" ``` -------------------------------- ### Class Definition with Constructor Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Define a class using the `class` keyword. The `new` method serves as the constructor. ```moonscript class Inventory new: => @items = {} ``` -------------------------------- ### Moonscript Table Comprehension - Copying Table Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md Create a copy of a table using a table comprehension, iterating over key-value pairs. The '{k,v for k,v in pairs thing}' syntax is used. ```moonscript thing = { color: "red" name: "fast" width: 123 } thing_copy = {k,v for k,v in pairs thing} ``` -------------------------------- ### Sample Output of Flags Parser Source: https://github.com/leafo/moonscript/wiki/Flags-Parser This is a sample output demonstrating the flags parser's behavior with specific command-line arguments. It shows how the parser correctly identifies and assigns values to flags, including a flag that requires a value (`-w`) and a boolean flag (`-t`). ```shell scratch$ moon test-flags.moon -w wlist -t {w:"wlist",t:true} ``` -------------------------------- ### MoonScript Single-Line While Loop Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md A concise syntax for while loops with a single statement body, using the 'do' keyword. ```moon while running == true do my_function! ``` -------------------------------- ### Accessing Class Instance Information in MoonScript Source: https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes Shows how to check the class of an instance using the '__class' property, which holds a reference to the class that created the instance. ```moonscript assert(b.__class == Person) ``` -------------------------------- ### Load MoonScript String with Options Source: https://github.com/leafo/moonscript/blob/master/docs/api.md Compile MoonScript strings using `moonscript.loadstring`, with an option to control implicit root return behavior. Setting `implicitly_return_root: false` prevents the last statement from being implicitly returned. ```moononly moonscript = require "moonscript.base" fn = moonscript.loadstring "10" print fn! -- prints "10" fn = moonscript.loadstring "10", implicitly_return_root: false print fn! -- prints nothing ``` -------------------------------- ### Run Function with Custom Environment Source: https://github.com/leafo/moonscript/blob/master/docs/standard_lib.md Execute a function within a mutated environment. The 'scope' table provides values, falling back to the original environment for missing keys. ```moon my_env = { secret_function: -> print "shhh this is secret" say_hi: -> print "hi there!" } say_hi = -> print "I am a closure" fn = -> secret_function! say_hi! run_with_scope fn, my_env ``` -------------------------------- ### MoonScript Single-Line For Loop Source: https://github.com/leafo/moonscript/blob/master/docs/reference.md A concise syntax for for loops where the body consists of a single statement, using the 'do' keyword. ```moon for item in *items do print item ``` ```moon for j = 1,10,3 do print j ```