### Lua Assignment Syntax and Examples Source: https://devdocs.io/lua/~5.4/index Demonstrates Lua's multiple assignment capabilities, showing how variables and expressions are matched and how values are adjusted (truncated or padded with nil). Includes examples of value swapping and cyclic permutation. ```lua stat ::= varlist ‘=’ explist varlist ::= var {‘,’ var} explist ::= exp {‘,’ exp} ``` ```lua i = 3 i, a[i] = i+1, 20 -- Sets a[3] to 20, i becomes 4 ``` ```lua x, y = y, x -- Swaps values of x and y ``` ```lua x, y, z = y, z, x -- Cyclically permutes values of x, y, and z ``` -------------------------------- ### Lua Assignment Example: Value Swapping and Update Source: https://devdocs.io/lua/index Illustrates Lua's multiple assignment capabilities with practical examples. It shows how to swap variable values and perform updates where a variable's current value is used in the assignment itself. ```lua i = 3 i, a[i] = i+1, 20 x, y = y, x x, y, z = y, z, x ``` -------------------------------- ### Lua Table Initialization Equivalent Source: https://devdocs.io/lua/~5.4/index Demonstrates the equivalent code for initializing a Lua table using explicit assignments. This example shows how the short-hand table constructor syntax translates into individual table assignments. ```lua do local t = {} t[f(1)] = g t[1] = "x" -- 1st exp t[2] = "y" -- 2nd exp t.x = 1 -- t["x"] = 1 t[3] = f(x) -- 3rd exp t[30] = 23 t[4] = 45 -- 4th exp a = t end ``` -------------------------------- ### Lua string.gsub with Function for Code Execution Source: https://devdocs.io/lua/~5.4/index Shows an advanced use of `string.gsub` where a function is provided for replacement. This example captures a string, loads it using `load`, and executes it to get the result, effectively evaluating expressions within the string. ```lua x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return load(s)() end) -- x will be "4+5 = 9" ``` -------------------------------- ### Lua Lexical Scoping Example Source: https://devdocs.io/lua/index Demonstrates Lua's lexical scoping rules. This example shows how global and local variables are accessed and modified within nested blocks, highlighting the behavior of 'x' in different scopes. ```lua x = 10 -- global variable do -- new block local x = x -- new 'x', with value 10 print(x) --> 10 x = x+1 do -- another block local x = x+1 -- another 'x' print(x) --> 12 end print(x) --> 11 end print(x) --> 10 (the global one) ``` -------------------------------- ### Example C Library Path - Lua Source: https://devdocs.io/lua/index Illustrates a typical format for the `package.cpath` variable, defining locations and filenames for C libraries that Lua's `require` function will search. ```lua "./?.so;./?.dll;/usr/local/?/init.so" ``` -------------------------------- ### Define Table Constructor in Lua Source: https://devdocs.io/lua/~5.4/index Shows the syntax for table constructors in Lua, used to create and initialize tables. Includes examples of different field types within the constructor. ```lua tableconstructor ::= ‘{’ [fieldlist] ‘}’ fieldlist ::= field {fieldsep field} [fieldsep] field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp fieldsep ::= ‘,’ | ‘;’ ``` -------------------------------- ### Execute Lua String Argument Example Source: https://devdocs.io/lua/~5.4/index Shows how to execute a Lua command specified directly as a string argument using the '-e' option, and how the `arg` table is populated when no script file is provided. ```bash $ lua -e "print(arg[1])" ``` -------------------------------- ### Lua Argument Table Example Source: https://devdocs.io/lua/~5.4/index Illustrates the structure of the global `arg` table in Lua when arguments are passed to the interpreter. It shows how interpreter options, script name, and script arguments are mapped to indices. ```bash $ lua -la b.lua t1 t2 arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" } ``` -------------------------------- ### Lua Logical Operator Examples Source: https://devdocs.io/lua/index Demonstrates the behavior of Lua's 'or' and 'and' logical operators, showcasing short-circuit evaluation and how they handle 'false' and 'nil' values. ```lua 10 or 20 --> 10 10 or error() --> 10 nil or "a" --> "a" nil and 10 --> nil false and error() --> false false and nil --> false false or nil --> nil 10 and 20 --> 20 ``` -------------------------------- ### Lua String Literals Example Source: https://devdocs.io/lua/~5.4/index Demonstrates different ways to represent the same string literal in Lua, including short strings with escape sequences and long bracketed strings. ```lua a = 'alo\n123"' a = "alo\n123\"" a = '\97lo\10\04923"' a = [[alo 123"]] a = [==[ alo 123"]==] ``` -------------------------------- ### Lua Shebang for Executable Scripts Source: https://devdocs.io/lua/~5.4/index Provides examples of using the shebang line (`#!`) at the beginning of a Lua script to make it directly executable on Unix-like systems. It shows both direct path and environment-based path resolution. ```bash #!/usr/local/bin/lua ``` ```bash #!/usr/bin/env lua ``` -------------------------------- ### Lua Coroutine Creation and Execution Example Source: https://devdocs.io/lua/~5.4/index Demonstrates the creation of a coroutine using `coroutine.create` and its subsequent execution via `coroutine.resume`. Shows how values are passed between the main thread and the coroutine during `resume` and `yield` operations, and how errors are handled. ```lua function foo (a) print("foo", a) return coroutine.yield(2*a) end co = coroutine.create(function (a,b) print("co-body", a, b) local r = foo(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end" end) print("main", coroutine.resume(co, 1, 10)) print("main", coroutine.resume(co, "r")) print("main", coroutine.resume(co, "x", "y")) print("main", coroutine.resume(co, "x", "y")) ``` -------------------------------- ### Lua Examples: Logical Operators (and, or, not) Source: https://devdocs.io/lua/~5.4/index Demonstrates the usage and short-circuit evaluation of Lua's logical 'and', 'or', and 'not' operators. Shows how they handle 'false' and 'nil' values, returning either the first operand or the second based on truthiness. ```lua print(10 or 20) print(10 or error()) print(nil or "a") print(nil and 10) print(false and error()) print(false and nil) print(false or nil) print(10 and 20) ``` -------------------------------- ### Lua Argument Table `arg` Example Source: https://devdocs.io/lua/index Illustrates how command-line arguments are populated into the global `arg` table in Lua. It shows the indexing of arguments, including the interpreter name, options, script name, and script arguments. ```lua -- Example: $ lua -la b.lua t1 t2 -- arg table will be: -- arg = { [-2] = "lua", [-1] = "-la", -- [0] = "b.lua", -- [1] = "t1", [2] = "t2" } ``` -------------------------------- ### Lua Closures and Upvalues Example Source: https://devdocs.io/lua/index Illustrates the creation of closures in Lua and how they interact with local variables ('upvalues'). Each closure created in the loop has its own 'y' but shares the same 'x'. ```lua a = {} local x = 20 for i = 1, 10 do local y = 0 a[i] = function () y = y + 1; return x + y end end ``` -------------------------------- ### Lua Multi-Value Return Handling Examples Source: https://devdocs.io/lua/~5.4/index Demonstrates how Lua handles multiple return values from function calls and vararg expressions in various contexts, including assignment, statement usage, and within table constructors. It shows how values are adjusted or discarded based on the surrounding expressions. ```lua f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) a,b = ... -- a gets the first vararg argument, b gets -- the second (both a and b can get nil if there -- is no corresponding vararg argument) a,b,c = x, f() -- f() is adjusted to 2 results a,b,c = f() -- f() is adjusted to 3 results return f() -- returns all results from f() return ... -- returns all received vararg arguments return x,y,f() -- returns x, y, and all results from f() {f()} -- creates a list with all results from f() {...} -- creates a list with all vararg arguments {f(), nil} -- f() is adjusted to 1 result ``` -------------------------------- ### Get Function Information with lua_getinfo (Lua) Source: https://devdocs.io/lua/index Retrieves detailed information about a function or function invocation using the lua_getinfo C API function. This example demonstrates how to get the line number where a global function 'f' is defined by pushing the function onto the stack and using the '>S' format string. ```c #include #include #include int get_function_line_defined(lua_State *L) { lua_Debug ar; lua_getglobal(L, "f"); /* get global 'f' */ if (lua_isfunction(L, -1)) { if (lua_getinfo(L, ">S", &ar)) { printf("%d\n", ar.linedefined); return 1; /* Indicate success, potentially return line number */ } else { fprintf(stderr, "Error calling lua_getinfo\n"); return 0; } } else { fprintf(stderr, "Global 'f' is not a function\n"); return 0; } } ``` -------------------------------- ### Execute Lua Script with Options Source: https://devdocs.io/lua/~5.4/index Demonstrates how to execute a Lua script with various command-line options, including executing a string, loading a library, and running a script file sequentially. This shows the order of option processing. ```bash $ lua -e 'a=1' -llib1 script.lua ``` -------------------------------- ### Lua String Manipulation: Get Character Codes Source: https://devdocs.io/lua/~5.4/index The `string.byte` function returns the numeric character codes for a given string segment. It takes a string `s` and optional start `i` and end `j` indices. Indices are 1-based and can be negative for reverse indexing. The numeric codes may not be portable across different platforms. ```lua string.byte (s [, i [, j]]) ``` -------------------------------- ### lua_createtable Source: https://devdocs.io/lua/index Creates a new, empty table and pushes it onto the Lua stack. Hints for array and hash part sizes can be provided for pre-allocation. ```APIDOC ## lua_createtable ### Description Creates a new, empty table and pushes it onto the top of the Lua stack. The parameters `narr` and `nrec` provide hints for the expected number of elements in the array and hash parts of the table, respectively, which can aid in pre-allocation for performance. ### Method `void lua_createtable (lua_State *L, int narr, int nrec);` ### Parameters - **L** (`lua_State*`) - The Lua state. - **narr** (`int`) - A hint for the number of elements in the array part. - **nrec** (`int`) - A hint for the number of elements in the non-array part. ### Result A new table is created and pushed onto the stack. ``` -------------------------------- ### Lua Shebang for Executable Scripts Source: https://devdocs.io/lua/index Provides examples of using the shebang line (`#!`) in Lua scripts to make them directly executable on Unix-like systems. It includes using a direct path to the Lua interpreter and a portable `env` approach. ```bash #!/usr/local/bin/lua #!/usr/bin/env lua ``` -------------------------------- ### lua_createtable Source: https://devdocs.io/lua/~5.4/index Creates a new, empty table and pushes it onto the stack. ```APIDOC ## lua_createtable ### Description Creates a new empty table and pushes it onto the Lua stack. The `narr` and `nrec` parameters provide hints for the expected number of elements in the array and hash parts, respectively, potentially optimizing memory preallocation. ### Method `void lua_createtable (lua_State *L, int narr, int nrec); ### Parameters - `L` (lua_State *) - The Lua state. - `narr` (int) - A hint for the number of elements in the array part of the table. - `nrec` (int) - A hint for the number of elements in the hash part of the table. ``` -------------------------------- ### Length Operator Source: https://devdocs.io/lua/index Function to get the length of a Lua value. ```APIDOC ## luaL_len ### Description Returns the "length" of the value at the given index as a number; it is equivalent to the '#' operator in Lua. Raises an error if the result of the operation is not an integer (this case can only happen through metamethods). ### Method `lua_Integer luaL_len (lua_State *L, int index); ` ### Parameters - **L** (lua_State *) - The Lua state. - **index** (int) - The index of the value on the stack. ``` -------------------------------- ### Open I/O Library Source: https://devdocs.io/lua/~5.4/index Opens the standard Lua input and output library. ```APIDOC ## luaopen_io ### Description Opens the standard Lua input and output library, providing functions for file operations. ### Method `luaopen_io` ### Parameters - **L** (lua_State *) - The Lua state in which to open the I/O library. ### Return Value - Returns 1, indicating success. ``` -------------------------------- ### Lua String Manipulation: Find Pattern or Substring Source: https://devdocs.io/lua/~5.4/index The `string.find` function searches for the first occurrence of a `pattern` within a string `s`. If found, it returns the start and end indices of the match; otherwise, it returns `fail`. An optional `init` argument specifies the starting position for the search, and a `plain` boolean argument disables pattern matching for a literal substring search. If the pattern includes captures, they are returned after the indices. ```lua string.find (s, pattern [, init [, plain]]) ``` -------------------------------- ### Raw Length Function Source: https://devdocs.io/lua/index Gets the raw length of a value on the stack. ```APIDOC ## `lua_rawlen` ### Description Returns the raw "length" of the value at the given index: for strings, this is the string length; for tables, this is the result of the length operator ('`#`') with no metamethods; for userdata, this is the size of the block of memory allocated for the userdata. For other values, this call returns 0. ### Method `lua_Unsigned lua_rawlen (lua_State *L, int index);` ### Parameters #### Path Parameters - **L** (lua_State *) - The Lua state. - **index** (int) - The stack index of the value. ### Response #### Success Response (lua_Unsigned) - Returns the raw length of the value. ``` -------------------------------- ### Create and Initialize Lua Table Source: https://devdocs.io/lua/~5.4/index Illustrates how to create and initialize a table in Lua using different field formats. The order of assignments in the constructor is undefined. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } ``` -------------------------------- ### Lua: Execute External Program and Read/Write Data with io.popen Source: https://devdocs.io/lua/index Starts a program in a separate process and returns a file handle for reading from or writing to the program's standard input/output. This function is system-dependent and may not be available on all platforms. ```lua -- Example: Reading output from a system command local file_handle = io.popen("ls -l", "r") if file_handle then local output = file_handle:read("*a") print(output) file_handle:close() else print("Error opening process") end -- Example: Writing to a system command's input local file_handle_write = io.popen("grep hello", "w") if file_handle_write then file_handle_write:write("hello world\n") file_handle_write:write("another line\n") file_handle_write:close() else print("Error opening process for writing") end ``` -------------------------------- ### Find Pattern in Lua String Source: https://devdocs.io/lua/index The `string.find` function searches for the first occurrence of a `pattern` within a string `s`. If found, it returns the starting and ending indices of the match; otherwise, it returns `nil`. An optional `init` argument specifies the starting position for the search, and a `plain` boolean argument can disable pattern matching for a literal substring search. If the pattern includes captures, their values are returned after the indices. ```lua string.find("hello world", "world") ``` ```lua string.find("hello world", "o", 5) ``` ```lua string.find("hello world", "o", 1, true) ``` -------------------------------- ### Lua Table Constructor Example Source: https://devdocs.io/lua/index Shows how to create tables in Lua using table constructors. This includes initializing tables with various field types: positional, named, and with explicit keys. A new table is created each time a constructor is evaluated. ```lua local emptyTable = {} local initializedTable = { key1 = "value1", [10] = "value10", "positional1", "positional2" } -- Equivalent to: -- do -- local t = {} -- t.key1 = "value1" -- t[10] = "value10" -- t[1] = "positional1" -- t[2] = "positional2" -- initializedTable = t -- end print(initializedTable.key1) -- Output: value1 print(initializedTable[1]) -- Output: positional1 print(initializedTable[10]) -- Output: value10 ``` -------------------------------- ### Open Package Library Source: https://devdocs.io/lua/~5.4/index Opens the standard Lua package library. ```APIDOC ## luaopen_package ### Description Opens the standard Lua package library, which handles module loading and management. ### Method `luaopen_package` ### Parameters - **L** (lua_State *) - The Lua state in which to open the package library. ### Return Value - Returns 1, indicating success. ``` -------------------------------- ### Coroutine Control: lua_resume Source: https://devdocs.io/lua/~5.4/index Starts and resumes a coroutine in a given Lua state. It handles pushing arguments, yielding, and error conditions during coroutine execution. ```APIDOC ## lua_resume ### Description Starts and resumes a coroutine in the given thread `L`. This function manages the execution flow between coroutines, handling arguments, yielded values, and potential errors. ### Method `int lua_resume (lua_State *L, lua_State *from, int nargs, int *nresults)` ### Parameters - **L** (`lua_State*`) - The Lua state (thread) to resume. - **from** (`lua_State*`) - The coroutine that is resuming `L`. Can be `NULL` if no coroutine is resuming. - **nargs** (`int`) - The number of arguments to be pushed onto the stack for the coroutine. - **nresults** (`int*`) - A pointer to store the number of results returned by the coroutine. ### Returns - `LUA_YIELD`: If the coroutine yields. - `LUA_OK`: If the coroutine finishes execution without errors. - An error code: In case of errors, with the error object on top of the stack. ``` -------------------------------- ### Open Base Library Source: https://devdocs.io/lua/~5.4/index Opens the standard Lua basic library. ```APIDOC ## luaopen_base ### Description Opens the standard Lua basic library, which provides core functions to Lua. ### Method `luaopen_base` ### Parameters - **L** (lua_State *) - The Lua state in which to open the basic library. ### Return Value - Returns 1, indicating success. ``` -------------------------------- ### Lua string.len Example Source: https://devdocs.io/lua/~5.4/index Demonstrates the `string.len` function in Lua, which returns the length of a given string. It correctly counts all characters, including embedded null characters. ```lua print(string.len("hello")) print(string.len("")) print(string.len("a\000bc\000")) ``` -------------------------------- ### Stack Manipulation Functions Source: https://devdocs.io/lua/index Functions for manipulating the Lua stack, including getting the length of values and loading chunks. ```APIDOC ## `lua_len` ### Description Returns the length of the value at the given index. It is equivalent to the '`#`' operator in Lua and may trigger a metamethod for the "length" event. The result is pushed on the stack. ### Method `void lua_len (lua_State *L, int index);` ### Parameters #### Path Parameters - **L** (`lua_State*`) - The Lua state. - **index** (`int`) - The stack index. ### Response #### Success Response The length of the value is pushed onto the stack. ``` ```APIDOC ## `lua_load` ### Description Loads a Lua chunk without running it. If there are no errors, it pushes the compiled chunk as a Lua function on top of the stack. Otherwise, it pushes an error message. It uses a user-supplied `reader` function to read the chunk. ### Method `int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname, const char *mode);` ### Parameters #### Path Parameters - **L** (`lua_State*`) - The Lua state. - **reader** (`lua_Reader`) - The function to read the chunk. - **data** (`void*`) - Opaque value passed to the reader function. - **chunkname** (`const char*`) - Name of the chunk for error messages. - **mode** (`const char*`) - Loading mode ('b' for binary, 't' for text, 'bt' for both). `NULL` is equivalent to "bt". ### Response #### Success Response (int) - **LUA_OK** - If the chunk is loaded successfully. - **LUA_ERRSYNTAX** - If there is a syntax error. - **LUA_ERRMEM** - If there is an out-of-memory error. - Other values may be returned corresponding to errors raised by the read function. ``` -------------------------------- ### Create Lua Tables with lua_createtable Source: https://devdocs.io/lua/~5.4/index Creates a new, empty Lua table and pushes it onto the stack. Provides hints for preallocating space for sequential and record elements to potentially improve performance. ```c void lua_createtable (lua_State *L, int narr, int nrec); ``` -------------------------------- ### Open OS Library Source: https://devdocs.io/lua/~5.4/index Opens the standard Lua operating system facilities library. ```APIDOC ## luaopen_os ### Description Opens the standard Lua operating system facilities library, providing access to OS-level functions. ### Method `luaopen_os` ### Parameters - **L** (lua_State *) - The Lua state in which to open the OS library. ### Return Value - Returns 1, indicating success. ``` -------------------------------- ### Get Hook Settings - Lua Source: https://devdocs.io/lua/~5.4/index Retrieves the current hook function, mask, and count for a given thread. Returns 'fail' if no hook is active. Used in conjunction with `debug.sethook`. ```lua local hookFunc, hookMask, hookCount = debug.gethook() if hookFunc then print("Hook function: ", hookFunc) print("Hook mask: ", hookMask) print("Hook count: ", hookCount) else print("No active hook.") end ``` -------------------------------- ### luaL_requiref Source: https://devdocs.io/lua/index Loads and sets up a Lua module, optionally storing it globally. ```APIDOC ## luaL_requiref ### Description If `package.loaded[modname]` is not true, calls the function `openf` with the string `modname` as an argument and sets the call result to `package.loaded[modname]`, as if that function has been called through `require`. If `glb` is true, also stores the module into the global `modname`. Leaves a copy of the module on the stack. ### Method N/A (C function) ### Parameters - **L** (`lua_State *`) - The Lua state. - **modname** (`const char *`) - The name of the module. - **openf** (`lua_CFunction`) - The function to open the module. - **glb** (`int`) - If true, store the module globally. ### Return Value None. ``` -------------------------------- ### Get Lua Hook Function Source: https://devdocs.io/lua/~5.4/index Retrieves the current hook function that is set for the Lua state. This function does not modify the stack or return values. It is part of the Lua debugging API. ```c lua_Hook lua_gethook (lua_State *L); ``` -------------------------------- ### luaL_prepbuffer and luaL_prepbuffsize Source: https://devdocs.io/lua/index Prepares a buffer for adding string content. ```APIDOC ## luaL_prepbuffer and luaL_prepbuffsize ### Description `luaL_prepbuffer` prepares a buffer `B` with a predefined size `LUAL_BUFFERSIZE`. `luaL_prepbuffsize` prepares a buffer `B` with a specified size `sz`. Both functions return a pointer to a memory space where you can copy a string to be added to the buffer. After copying, `luaL_addsize` must be called with the string's size. ### Method N/A (C functions) ### Parameters - **B** (`luaL_Buffer *`) - The buffer to prepare. - **sz** (`size_t`) - The size of the space to prepare (for `luaL_prepbuffsize`). ### Return Value - `char *` - A pointer to the allocated space in the buffer. ``` -------------------------------- ### Get Lua Version (Lua C API) Source: https://devdocs.io/lua/~5.4/index The lua_version function returns the version number of the Lua core. This can be useful for compatibility checks when integrating Lua into C applications. ```c lua_Number lua_version (lua_State *L); ``` -------------------------------- ### Lua Function Definition Syntactic Sugar Source: https://devdocs.io/lua/index Demonstrates Lua's syntactic sugar for defining functions, both globally and locally. It shows how shorthand notations translate into explicit 'function' keyword usage. ```lua function f () body end -- translates to f = function () body end ``` ```lua function t.a.b.c.f () body end -- translates to t.a.b.c.f = function () body end ``` ```lua local function f () body end -- translates to local f; f = function () body end ``` -------------------------------- ### Open All Standard Libraries Source: https://devdocs.io/lua/~5.4/index Opens all standard Lua libraries, making them available in the Lua state. ```APIDOC ## luaL_openlibs ### Description Opens all standard Lua libraries, making them available in the Lua state. This includes the basic, coroutine, package, string, UTF-8, table, math, I/O, operating system, and debug libraries. ### Method `luaL_openlibs` ### Parameters - **L** (lua_State *) - The Lua state in which to open the libraries. ``` -------------------------------- ### lua_resume - Coroutine Management Source: https://devdocs.io/lua/index Starts and resumes a coroutine in the given thread. It handles pushing arguments, managing results, and error reporting. ```APIDOC ## lua_resume ### Description Starts and resumes a coroutine in the given thread `L`. This function is used to initiate a coroutine by pushing its main function and arguments, or to resume a suspended coroutine by providing new arguments. ### Method `int lua_resume (lua_State *L, lua_State *from, int nargs, int *nresults);` ### Parameters * **L** (`lua_State*`) - The coroutine thread to resume. * **from** (`lua_State*`) - The coroutine that is resuming `L`, or NULL if none. * **nargs** (`int`) - The number of arguments to push onto the stack for the resumed coroutine. * **nresults** (`int*`) - Pointer to an integer that will be updated with the number of results returned by the coroutine. ### Return Value * `LUA_YIELD` if the coroutine yields. * `LUA_OK` if the coroutine finishes without errors. * An error code in case of errors. The error object will be on the top of the stack. ``` -------------------------------- ### C: Implementing continuation function structure Source: https://devdocs.io/lua/~5.4/index This C code demonstrates the basic structure of a continuation function (`k`) which is designed to handle the post-yield execution. It receives the Lua state, status, and context, and should contain the logic that was originally intended to run after the `lua_pcall`. ```c int k (lua_State *L, int status, lua_KContext ctx) { ... /* code 2 */ } ``` -------------------------------- ### Get Temporary Filename in Lua Source: https://devdocs.io/lua/index Generates a unique filename suitable for temporary files. The file must be explicitly opened and removed by the user. ```lua local tempFileName = os.tmpname() print(tempFileName) -- Remember to open and remove the file explicitly ``` -------------------------------- ### Lua C API Overview Source: https://devdocs.io/lua/~5.4/index This section provides a general overview of the Lua C API, including its purpose, header file, reentrancy, and the role of the Lua state and threads. ```APIDOC ## Lua C API Overview ### Description This section describes the C API for Lua, which is the set of C functions available to the host program to communicate with Lua. All API functions, related types, and constants are declared in the header file `lua.h`. ### Key Concepts - **Reentrancy**: The Lua library is fully reentrant and has no global variables. All necessary information is stored in a dynamic structure called the _Lua state_. - **Lua State**: A `lua_State` pointer represents a thread, which indirectly refers to the Lua state associated with that thread. A pointer to a thread must be passed as the first argument to every API function, except `lua_newstate`. - **Argument Checking**: By default, Lua API functions do not check arguments for validity. This behavior can be enabled by compiling Lua with `LUA_USE_APICHECK` defined. - **Macros**: API facilities may be provided as macros instead of functions. These macros generally use each argument exactly once, avoiding hidden side-effects. ``` -------------------------------- ### Get Function Information - Lua Source: https://devdocs.io/lua/~5.4/index Returns a table containing information about a function or a call stack level. The `what` parameter specifies which fields to retrieve. Can inspect current function or caller functions. ```lua local infoAboutPrint = debug.getinfo(print, "nu"); print(string.format("Name: %s, What: %s", infoAboutPrint.name or "", infoAboutPrint.what)) local infoAboutCurrentFunc = debug.getinfo(0, "fL") print("Current function info:", infoAboutCurrentFunc) local infoAboutCaller = debug.getinfo(1, "n") print("Caller function name: ", infoAboutCaller.name or "") ``` -------------------------------- ### Get Lua Hook Count Source: https://devdocs.io/lua/~5.4/index Retrieves the current hook count value for the Lua state. This count determines how often the hook function is called. It does not affect the stack or return values. ```c int lua_gethookcount (lua_State *L); ``` -------------------------------- ### Get Stack Top Index (C) Source: https://devdocs.io/lua/~5.4/index Returns the index of the top element on the Lua stack. This value is equal to the number of elements currently in the stack, with 0 indicating an empty stack. ```c int lua_gettop (lua_State *L); ``` -------------------------------- ### Lua: Unpack Table Elements Source: https://devdocs.io/lua/~5.4/index The `table.unpack` function returns elements from a list-like table. It allows specifying a start and end index for unpacking. By default, it unpacks all elements from the first to the last. ```lua local list = {"apple", "banana", "cherry"} local first, second, third = table.unpack(list) print(first, second, third) -- Output: apple banana cherry local numbers = {10, 20, 30, 40, 50} local subset = {table.unpack(numbers, 2, 4)} print(table.concat(subset, ", ")) -- Output: 20, 30, 40 ``` -------------------------------- ### Table and Userdata Creation Functions Source: https://devdocs.io/lua/index Functions for creating new Lua tables and user data. ```APIDOC ## `lua_newtable` ### Description Creates a new empty table and pushes it onto the stack. It is equivalent to `lua_createtable(L, 0, 0)`. ### Method `void lua_newtable (lua_State *L);` ### Parameters #### Path Parameters - **L** (`lua_State*`) - The Lua state. ### Response #### Success Response A new empty table is pushed onto the stack. ``` ```APIDOC ## `lua_newuserdatauv` ### Description Creates and pushes on the stack a new full userdata, with `nuvalue` associated Lua values (user values), plus an associated block of raw memory with `size` bytes. ### Method `void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue);` ### Parameters #### Path Parameters - **L** (`lua_State*`) - The Lua state. - **size** (`size_t`) - The size of the memory block. - **nuvalue** (`int`) - The number of user values. ### Response #### Success Response (`void*`) - The address of the block of memory. ### Details Lua ensures that this address is valid as long as the corresponding userdata is alive. If the userdata is marked for finalization, its address is valid at least until the call to its finalizer. ``` -------------------------------- ### Lua String Captures with Pattern Matching Source: https://devdocs.io/lua/index Demonstrates how parentheses in Lua patterns create capture groups, storing matched substrings. It also illustrates the behavior of string.gsub with multiple matches, particularly regarding empty string matches and position tracking. ```lua -- Example of captures: -- pattern = "(a*(.)%w(%s*))" -- In this pattern: -- 1 captures "a*(.)%w(%s*)" -- 2 captures the character matching "." -- 3 captures the substring matching "%s*" -- Special case: () captures the current string position (a number) -- string.gmatch("flaaap", "()aa()") yields captures 3 and 5 -- Example with string.gsub and multiple matches: -- string.gsub("abc", "()a*()", print) -- Output illustrates how Lua handles consecutive matches and empty strings. ``` -------------------------------- ### Lua string.gsub for Swapping Words Source: https://devdocs.io/lua/~5.4/index Illustrates using `string.gsub` to reorder captured groups. This example swaps the order of two adjacent words, using `%2` and `%1` to refer to the captured groups. ```lua x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") -- x will be "world hello Lua from" ``` -------------------------------- ### Opening Standard Lua Libraries - luaL_openlibs (C) Source: https://devdocs.io/lua/~5.4/index Opens all standard Lua libraries into the provided Lua state, making them available for use within Lua scripts. ```c void luaL_openlibs (lua_State *L); ``` -------------------------------- ### Get Hook Settings in Lua Source: https://devdocs.io/lua/index Retrieves the current hook function, mask, and count for a given thread. Returns 'fail' if no active hook is set. ```lua local hookFunc, hookMask, hookCount = debug.gethook() if hookFunc then print('Hook is active') else print('No active hook') end ``` -------------------------------- ### Lua: Get CPU Time Used by the Program (os.clock) Source: https://devdocs.io/lua/~5.4/index Returns an approximation of the CPU time in seconds used by the current program. This value is based on the underlying ISO C `clock` function. ```lua local start_time = os.clock() -- Simulate some work for i = 1, 1000000 do math.sqrt(i) end local end_time = os.clock() local cpu_time_used = end_time - start_time print(string.format("CPU time used: %.4f seconds\n", cpu_time_used)) ``` -------------------------------- ### luaL_buffinitsize Source: https://devdocs.io/lua/index Initializes a buffer and preallocates a specified size. ```APIDOC ## luaL_buffinitsize ### Description Equivalent to the sequence `luaL_buffinit`, `luaL_prepbuffsize`. Initializes a buffer and preallocates space for `sz` bytes. ### Method `char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz);` ### Parameters - **L** (`lua_State*`) - The Lua state. - **B** (`luaL_Buffer*`) - The buffer to initialize. - **sz** (`size_t`) - The size of the space to preallocate. ``` -------------------------------- ### Get Lua Allocator Function with lua_getallocf Source: https://devdocs.io/lua/~5.4/index Retrieves the memory allocation function currently used by a Lua state. Optionally, it can also return the opaque user data pointer associated with the allocator. ```c lua_Alloc lua_getallocf (lua_State *L, void **ud); ``` -------------------------------- ### Lua Standalone Interpreter Command-Line Options Source: https://devdocs.io/lua/index A list of common command-line options for the Lua standalone interpreter, detailing their functions such as executing strings, entering interactive mode, loading modules, and displaying version information. ```bash lua -e '_stat_' # execute string _stat_ lua -i # enter interactive mode after running script lua -l _mod_ # require _mod_ and assign the result to global _mod_ lua -v # print version information lua -E # ignore environment variables lua -W # turn warnings on lua -- # stop handling options lua - # execute stdin as a file and stop handling options ``` -------------------------------- ### Lua C API: Get Absolute Index Source: https://devdocs.io/lua/~5.4/index Converts an acceptable stack index to an absolute index, ensuring it's independent of the stack top. Returns an integer representing the absolute index. ```c int lua_absindex (lua_State *L, int idx); ``` -------------------------------- ### Lua string.gsub for Simple Word Repetition Source: https://devdocs.io/lua/~5.4/index Demonstrates `string.gsub` to replace occurrences of a pattern with a modified string. This example repeats each matched word twice, separated by a space, using capture group `%1`. ```lua x = string.gsub("hello world", "(%w+)", "%1 %1") -- x will be "hello hello world world" ``` -------------------------------- ### luaL_prepbuffer and luaL_prepbuffsize Source: https://devdocs.io/lua/~5.4/index Prepares a buffer for adding string data. `luaL_prepbuffsize` allows specifying the size, while `luaL_prepbuffer` uses a predefined size. ```APIDOC ## luaL_prepbuffer and luaL_prepbuffsize ### Description These functions return an address to a space of a specified size where you can copy a string to be added to a buffer. After copying, `luaL_addsize` must be called with the string's size. ### Method N/A (C functions) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A (Returns a char *) #### Response Example N/A ``` -------------------------------- ### Lua Standalone Interpreter Usage Source: https://devdocs.io/lua/index The basic command-line syntax for executing Lua scripts using the standalone interpreter. It shows how to pass options, a script file, and arguments to the interpreter. ```bash lua [options] [script [args]] ``` -------------------------------- ### Get the length of a Lua value Source: https://devdocs.io/lua/~5.4/index The `lua_len` function retrieves the length of the value at the specified stack index. It mimics the behavior of the Lua '#' operator and may invoke metamethods. The result is pushed onto the stack. ```c void lua_len (lua_State *L, int index); // Returns the length of the value at the given index. It is equivalent to the '`#`' operator in Lua (see §3.4.7) and may trigger a metamethod for the "length" event (see §2.4). The result is pushed on the stack. ``` -------------------------------- ### Open Math Library Source: https://devdocs.io/lua/~5.4/index Opens the standard Lua mathematical functions library. ```APIDOC ## luaopen_math ### Description Opens the standard Lua mathematical functions library, providing functions like sin, log, etc. ### Method `luaopen_math` ### Parameters - **L** (lua_State *) - The Lua state in which to open the math library. ### Return Value - Returns 1, indicating success. ``` -------------------------------- ### Get Metatable of Value (C) Source: https://devdocs.io/lua/~5.4/index Pushes the metatable of a value onto the stack if it exists. It returns 1 if a metatable is found and pushed, and 0 otherwise. It takes the Lua state and the index of the value as input. ```c int lua_getmetatable (lua_State *L, int index); ``` -------------------------------- ### State and Thread Creation Functions Source: https://devdocs.io/lua/index Functions for creating new Lua states and threads. ```APIDOC ## `lua_newstate` ### Description Creates a new independent state and returns its main thread. Returns `NULL` if it cannot create the state (due to lack of memory). ### Method `lua_State *lua_newstate (lua_Alloc f, void *ud);` ### Parameters #### Path Parameters - **f** (`lua_Alloc`) - The allocator function. - **ud** (`void*`) - An opaque pointer passed to the allocator. ### Response #### Success Response (`lua_State*`) - A pointer to the new Lua state's main thread. #### Error Response (`NULL`) - If the state cannot be created due to lack of memory. ``` ```APIDOC ## `lua_newthread` ### Description Creates a new thread, pushes it on the stack, and returns a pointer to a `lua_State` that represents this new thread. The new thread shares its global environment with the original thread but has an independent execution stack. ### Method `lua_State *lua_newthread (lua_State *L);` ### Parameters #### Path Parameters - **L** (`lua_State*`) - The Lua state. ### Response #### Success Response (`lua_State*`) - A pointer to the new thread's `lua_State`. ### Details Threads are subject to garbage collection. ``` -------------------------------- ### Get Global Variable Value (C) Source: https://devdocs.io/lua/~5.4/index Pushes the value of a global variable onto the Lua stack. It takes the Lua state and the name of the global variable as input and returns the type of the value pushed. ```c int lua_getglobal (lua_State *L, const char *name); ``` -------------------------------- ### lua_yieldk - Yield Coroutine Source: https://devdocs.io/lua/~5.4/index Yields a coroutine (thread) from a C function. It suspends the coroutine's execution and returns control to the `lua_resume` call that started it. The coroutine can be resumed later by calling a continuation function. ```APIDOC ## `lua_yieldk` ### Description Yields a coroutine (thread). When a C function calls `lua_yieldk`, the running coroutine suspends its execution, and the call to `lua_resume` that started this coroutine returns. The parameter `nresults` is the number of values from the stack that will be passed as results to `lua_resume`. When the coroutine is resumed again, Lua calls the given continuation function `k` to continue the execution of the C function that yielded. This continuation function receives the same stack from the previous function, with the `n` results removed and replaced by the arguments passed to `lua_resume`. Moreover, the continuation function receives the value `ctx` that was passed to `lua_yieldk`. ### Method `lua_yieldk` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **L** (`lua_State *`) - Required - The current Lua state. - **nresults** (`int`) - Required - The number of results to return to `lua_resume`. - **ctx** (`lua_KContext`) - Required - The context to pass to the continuation function. - **k** (`lua_KFunction`) - Required - The continuation function to call when the coroutine is resumed. ### Request Example ```c int my_c_function(lua_State *L) { // ... some operations ... return lua_yieldk(L, num_results, context, continuation_function); } ``` ### Response #### Success Response (Yield) This function typically does not return directly when yielding. Execution resumes in the continuation function `k`. #### Response Example N/A (Function yields control) ``` -------------------------------- ### Loading and Running Lua Code Source: https://devdocs.io/lua/index Functions for loading and executing Lua scripts from files or strings. ```APIDOC ## luaL_dofile ### Description Loads and runs the given file. It is defined as the following macro: `(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))`. It returns `LUA_OK` if there are no errors, or an error code in case of errors. ### Method `int luaL_dofile (lua_State *L, const char *filename); ` ### Parameters - **L** (lua_State *) - The Lua state. - **filename** (const char *) - The name of the file to load and run. ``` ```APIDOC ## luaL_dostring ### Description Loads and runs the given string. It is defined as the following macro: `(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))`. It returns `LUA_OK` if there are no errors, or an error code in case of errors. ### Method `int luaL_dostring (lua_State *L, const char *str); ` ### Parameters - **L** (lua_State *) - The Lua state. - **str** (const char *) - The string containing Lua code to load and run. ``` ```APIDOC ## luaL_loadbuffer ### Description Equivalent to `luaL_loadbufferx` with `mode` equal to `NULL`. ### Method `int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name); ` ### Parameters - **L** (lua_State *) - The Lua state. - **buff** (const char *) - The buffer containing the Lua code. - **sz** (size_t) - The size of the buffer. - **name** (const char *) - The name of the buffer for error messages. ```