### Lua Command Execution Example Source: https://lua.org/manual/5.5/manual Illustrates a typical command-line invocation of the Lua interpreter, showing the order of execution for options, library loading, and script execution. This example demonstrates a common workflow for running Lua scripts with specific configurations. ```bash $ lua -e 'a=1' -llib1 script.lua ``` -------------------------------- ### Lua Auxiliary Library: Allocation Function Example Source: https://lua.org/manual/5.5/manual Provides a simple implementation for the memory-allocator function using `realloc` and `free`. This example function, `luaL_alloc`, demonstrates how to handle zero-sized allocations for freeing memory. ```c void *luaL_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } ``` -------------------------------- ### Lua Function Call Argument Mapping Examples Source: https://lua.org/manual/5.5/manual Demonstrates how arguments in function calls are mapped to parameters and how variadic arguments are handled. ```lua function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end -- Call mapping examples: -- f(3) -> a=3, b=nil -- f(3, 4) -> a=3, b=4 -- f(3, 4, 5) -> a=3, b=4 -- f(r(), 10) -> a=1, b=10 -- f(r()) -> a=1, b=2 -- g(3) -> a=3, b=nil, va. table -> {n = 0} -- g(3, 4) -> a=3, b=4, va. table -> {n = 0} -- g(3, 4, 5, 8) -> a=3, b=4, va. table -> {5, 8, n = 2} -- g(5, r()) -> a=5, b=1, va. table -> {2, 3, n = 2} ``` -------------------------------- ### Lua Function Definition Translation Examples Source: https://lua.org/manual/5.5/manual Shows how simplified function definition statements translate into their equivalent explicit function expressions. ```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 ``` ```lua global function f () _body_ end -- translates to global f; global f = function () _body_ end ``` ```lua function t.a.b.c:f (_params_) _body_ end -- is syntactic sugar for t.a.b.c.f = function (self, _params_) _body_ end ``` -------------------------------- ### Lua Comments Source: https://lua.org/manual/5.5/manual Demonstrates Lua's comment syntax. Short comments start with '--' and run to the end of the line. Long comments start with '--[[' and end with ']]'. ```lua -- This is a short comment. --[[ This is a long comment. ]] ``` -------------------------------- ### Lua Table Constructor Example Source: https://lua.org/manual/5.5/manual Illustrates the usage of Lua table constructors with various field initializations, including explicit key-value pairs, named fields, and sequential array-like fields. It also shows the equivalent expanded code. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } is equivalent to 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 Coroutine Execution Example Source: https://lua.org/manual/5.5/manual Demonstrates the creation, resumption, and yielding of Lua coroutines. It shows how values are passed between the main thread and the coroutine, and how errors are handled when resuming a dead coroutine. The output illustrates the step-by-step execution and communication. ```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 Interactive Mode Prompt Example Source: https://lua.org/manual/5.5/manual Demonstrates the behavior of Lua's interactive mode, including how it handles global variables versus local variables across lines and how it prompts for incomplete chunks. This highlights the nuances of interactive execution and the warnings issued for local variable scope issues. ```lua > x = 20 -- global 'x' > local x = 10; print(x) --> warning: locals do not survive across lines in interactive mode --> 10 > print(x) -- back to global 'x' --> 20 > do -- incomplete chunk >> local x = 10; print(x) -- '>>' prompts for line completion >> print(x) >> end -- chunk completed --> 10 --> 10 ``` -------------------------------- ### Lua string.gsub Multiple Matches Example Source: https://lua.org/manual/5.5/manual Demonstrates how string.gsub handles multiple matches of a pattern, particularly when empty strings are involved. It highlights that a new match must end at least one byte after the previous one. ```lua string.gsub("abc", "()a*()", print) -- Expected output: -- > 1 2 -- > 3 3 -- > 4 4 ``` -------------------------------- ### Lua Global Declaration Example Source: https://lua.org/manual/5.5/manual Demonstrates the usage of collective global declarations, including 'global X' and 'global *'. It shows how these declarations affect the read-write access of variables and the implications for built-in functions. ```lua global X global * print(math.pi) -- Ok, 'print' and 'math' are read-only X = 1 -- Ok, declared as read-write Y = 1 -- Error, Y is read-only ``` -------------------------------- ### Lua Logical Operators Examples Source: https://lua.org/manual/5.5/manual Demonstrates the behavior of Lua's 'and', 'or', and 'not' logical operators. These operators treat 'false' and 'nil' as false, and all other values as true. They utilize short-circuit evaluation. ```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 ``` -------------------------------- ### Traverse Table Entries (Lua) Source: https://lua.org/manual/5.5/manual Allows iteration over all key-value pairs in a Lua table. `next` returns the subsequent index and value, starting with `nil` to get the first pair. `pairs` provides a convenient iterator for `for` loops, optionally using a `__pairs` metamethod. Modifying the table during traversal is cautioned against. ```lua local my_table = { a = 1, b = 2 } local k, v = next(my_table, nil) while k do print(k, v) k, v = next(my_table, k) end ``` ```lua local my_table = { name = "Lua", version = 5.5 } for key, value in pairs(my_table) do print(key, value) end ``` -------------------------------- ### Get Lua Memory Allocator (C API) Source: https://lua.org/manual/5.5/manual The `lua_getallocf` function retrieves the memory allocator function associated with a Lua state. If a pointer to a `void*` is provided, it will also store the opaque pointer used during the allocator's setup. This is useful for understanding or modifying memory management within Lua. ```c lua_Alloc lua_getallocf (lua_State *L, void **ud); ``` -------------------------------- ### luaL_prepbuffer and luaL_prepbuffsize Source: https://lua.org/manual/5.5/manual Prepares a buffer for adding strings. `luaL_prepbuffer` uses a predefined size, while `luaL_prepbuffsize` allows specifying the size. ```APIDOC ## luaL_prepbuffer / luaL_prepbuffsize ### Description Returns an address to a space of a specified size (`sz` for `luaL_prepbuffsize`, `LUAL_BUFFERSIZE` for `luaL_prepbuffer`) where you can copy a string to be added to a `luaL_Buffer`. After copying, you must call `luaL_addsize` with the string's size. ### Method `char *luaL_prepbuffer (luaL_Buffer *B);` `char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz);` ### Parameters - **B** (`luaL_Buffer *`) - The buffer to prepare. - **sz** (`size_t`) - The size of the space to allocate (for `luaL_prepbuffsize`). ### Return Value - `char *` - A pointer to the allocated space in the buffer. ``` -------------------------------- ### Prepare Buffer for String Addition (Lua C API) Source: https://lua.org/manual/5.5/manual Prepares a buffer to add a string by returning a pointer to a memory space of a specified size. After copying the string, luaL_addsize must be called to finalize the addition. ```c char *luaL_prepbuffsize (lua_State *L, size_t sz); ``` -------------------------------- ### Lua Non-Tail Call Examples Source: https://lua.org/manual/5.5/manual Provides examples of function calls that are explicitly not tail calls in Lua, even if they involve `return` and a function call. These include cases where results are modified, additional arguments are present, or the call is part of a larger expression. ```lua return (f(x)) -- results adjusted to 1 return 2 * f(x) -- result multiplied by 2 return x, f(x) -- additional results f(x); return -- results discarded return x or f(x) -- results adjusted to 1 ``` -------------------------------- ### Create Lua Table Source: https://lua.org/manual/5.5/manual Creates a new empty table and pushes it onto the Lua stack. `lua_createtable` accepts hints for sequence and record elements to potentially optimize memory preallocation. ```c void lua_createtable (lua_State *L, int nseq, int nrec); ``` -------------------------------- ### Get Environment Variable Source: https://lua.org/manual/5.5/manual Retrieves the value of a process environment variable. ```APIDOC ## os.getenv (varname) ### Description Returns the value of the process environment variable specified by `varname`. ### Method `os.getenv` ### Parameters #### Path Parameters - `varname` (string) - Required - The name of the environment variable to retrieve. ### Response #### Success Response - Returns `value` (string) - The value of the environment variable. #### Error Response - Returns `fail` (boolean) - `false` if the variable is not defined. ``` -------------------------------- ### Resume Coroutine Execution (C) Source: https://lua.org/manual/5.5/manual Starts or resumes the execution of a coroutine in the Lua state 'L'. It takes the number of arguments 'nargs' for starting a coroutine and updates 'nresults' with the number of values returned or yielded. It handles yielding, successful completion, and errors, returning specific status codes. ```c int lua_resume (lua_State *L, lua_State *from, int nargs, int *nresults); ``` -------------------------------- ### require (modname) Source: https://lua.org/manual/5.5/manual Loads a module. ```APIDOC ## require (modname) ### Description Loads the given module. It checks `package.loaded` for pre-loaded modules. If not found, it searches for a loader using `package.preload`, `package.path` for Lua loaders, `package.cpath` for C loaders, and finally an all-in-one loader. The loader is called with the module name and loader data. The returned value is stored in `package.loaded` and returned by `require`. Errors during loading or if no loader is found will raise an error. ### Method POST ### Endpoint `/modules/require` ### Parameters #### Request Body - **modname** (string) - Required - The name of the module to load. ### Request Example ```json { "modname": "my_module" } ``` ### Response #### Success Response (200) - **module_value** (any) - The loaded module's value. - **loader_data** (any) - Data returned by the searcher. ``` -------------------------------- ### string.sub Source: https://lua.org/manual/5.5/manual Extracts a substring from a given string based on start and end indices. ```APIDOC ## string.sub (s, i [, j]) ### Description Returns the substring of `s` that starts at index `i` and continues until index `j`. Indices can be negative. If `j` is omitted, it defaults to -1 (the end of the string). ### Method `string.sub` ### Parameters #### Path Parameters - **s** (string) - The string to extract the substring from. - **i** (number) - The starting index. - **j** (number, optional) - The ending index. Defaults to -1. ### Response #### Success Response - (string) - The extracted substring. Returns an empty string if `i` is greater than `j` after index correction. ``` -------------------------------- ### Lua String Pattern Matching Source: https://lua.org/manual/5.5/manual Searches for the first occurrence of a pattern within a string 's'. Returns the start and end indices of the match, or 'fail' if no match is found. Optional 'init' and 'plain' arguments control the starting position and disable pattern matching respectively. Captured values from the pattern are also returned on success. ```lua string.find(s, pattern, init, plain) ``` -------------------------------- ### Lua Interpreter Command-Line Usage Source: https://lua.org/manual/5.5/manual Demonstrates the basic syntax for invoking the Lua interpreter with options, a script, and arguments. This is the primary way to execute Lua code from the command line. ```bash lua [options] [script [args]] ``` -------------------------------- ### string.find Source: https://lua.org/manual/5.5/manual Searches for the first occurrence of a pattern within a string and returns its start and end indices. ```APIDOC ## `string.find (s, pattern [, init [, plain]])` ### Description Looks for the first match of `pattern` in the string `s`. If it finds a match, then `find` returns the indices of `s` where this occurrence starts and ends; otherwise, it returns **fail**. A third, optional numeric argument `init` specifies where to start the search; its default value is 1 and can be negative. A **true** as a fourth, optional argument `plain` turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in `pattern` being considered magic. If the pattern has captures, then in a successful match the captured values are also returned, after the two indices. ### Method (Implicitly a function call, not a typical HTTP method) ### Endpoint (N/A - this is a library function) ### Parameters #### Path Parameters (N/A) #### Query Parameters (N/A) #### Request Body (N/A) ### Request Example (N/A - this is a function call, not a request body) ### Response #### Success Response - **number** - The starting index of the match. - **number** - The ending index of the match. - (Optional) **any** - Captured values if the pattern contains captures. #### Failure Response - **nil** - If no match is found. #### Response Example (N/A - function return values vary) ``` -------------------------------- ### Type Checking and Information Source: https://lua.org/manual/5.5/manual Functions to determine the type of a Lua value and to get the name of a type. ```APIDOC ## `lua_type` ### Description Returns the type of the value in the given valid index. Returns `LUA_TNONE` for invalid indices. ### Method `int lua_type (lua_State *L, int index); ` ### Parameters - **L** (`lua_State*`) - The Lua state. - **index** (`int`) - The index of the value on the stack. ### Response Example ```json { "example": "// Returns an integer code representing the type (e.g., LUA_TSTRING)" } ``` ## `lua_typename` ### Description Returns the name of the type encoded by the given type code. ### Method `const char *lua_typename (lua_State *L, int tp); ` ### Parameters - **L** (`lua_State*`) - The Lua state. - **tp** (`int`) - The type code (e.g., from `lua_type`). ### Response Example ```json { "example": "// Returns the string name of the type (e.g., \"string\")" } ``` ``` -------------------------------- ### package.path Source: https://lua.org/manual/5.5/manual A string representing the path `require` uses to search for Lua loaders. ```APIDOC ## `package.path` ### Description This variable is a string containing the path `require` uses to search for Lua module files. At startup, it is initialized based on the `LUA_PATH_5_5` or `LUA_PATH` environment variables, or a default path defined in `luaconf.h`. ### Method Read/Write variable ### Endpoint N/A (Global variable) ### Parameters None ### Request Example ```lua -- View the current Lua path print(package.path) -- Modify the Lua path (use with caution) package.path = "./?.lua; " .. package.path ``` ### Response #### Success Response (200) - **string** - The current search path for Lua modules. #### Response Example ```lua ./?.lua;/usr/local/share/lua/5.5/?.lua;/usr/local/share/lua/5.5/?/init.lua ``` ``` -------------------------------- ### Create and Register Library with luaL_newlib and luaL_newlibtable Source: https://lua.org/manual/5.5/manual Creates a new table and registers functions from a provided list `l`. luaL_newlib uses luaL_newlibtable and luaL_setfuncs. luaL_newlibtable creates a table optimized for the entries in `l` but doesn't store them. The array `l` must be the actual array, not a pointer. ```c void luaL_newlib (lua_State *L, const luaL_Reg l[]); void luaL_newlibtable (lua_State *L, const luaL_Reg l[]); ``` -------------------------------- ### Lua Integer Constants Source: https://lua.org/manual/5.5/manual Examples of valid integer constants in Lua. These include decimal integers and hexadecimal integers. ```lua 3 345 0xff 0xBEBADA ``` -------------------------------- ### package.loaded Source: https://lua.org/manual/5.5/manual Table for tracking loaded modules. ```APIDOC ## package.loaded ### Description A table used by `require` to keep track of loaded modules. If `package.loaded[modname]` is not false, `require` returns the stored value immediately. Assignments to `package.loaded` do not affect the internal table used by `require`, which is stored in the C registry under the key `LUA_LOADED_TABLE`. ### Method GET ### Endpoint `/package/loaded` ### Response #### Success Response (200) - **loaded_modules** (table) - A table containing modules that have been loaded. ``` -------------------------------- ### Get Lua Core Version (lua_version) Source: https://lua.org/manual/5.5/manual Returns the version number of the Lua core. The return type is lua_Number. ```c lua_Number lua_version (lua_State *L); ``` -------------------------------- ### debug.setupvalue Source: https://lua.org/manual/5.5/manual Assigns a value to an upvalue of a given function. ```APIDOC ## PUT debug.setupvalue ### Description Assigns the `value` to the upvalue with index `up` of the function `f`. Returns the name of the upvalue if successful, or **fail** if the index is invalid. ### Method PUT ### Endpoint `/websites/lua_manual_5_5/debug/setupvalue` ### Parameters #### Path Parameters - **f** (function) - The function containing the upvalue. - **up** (number) - The index of the upvalue (1-based). #### Request Body - **value** (any) - The value to assign to the upvalue. ### Response #### Success Response (200) - **name** (string) - The name of the modified upvalue. #### Response Example ```json { "name": "closureVar" } ``` ``` -------------------------------- ### Get Pseudo-index for Upvalue (lua_upvalueindex) Source: https://lua.org/manual/5.5/manual Returns the pseudo-index representing the i-th upvalue of the current function. `i` must be between 1 and 256. ```c int lua_upvalueindex (int i); ``` -------------------------------- ### package.loadlib Source: https://lua.org/manual/5.5/manual Dynamically links the host program with a C library and can return a specific function from it. ```APIDOC ## `package.loadlib` (libname, funcname) ### Description Dynamically links the host program with the C library `libname`. If `funcname` is "*", it only links. Otherwise, it looks for a function `funcname` inside the library and returns it as a C function adhering to the `lua_CFunction` prototype. This is a low-level function that bypasses the standard package and module system, requiring the full library path and exact function name. ### Method `package.loadlib` ### Endpoint N/A (Internal Lua function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```lua -- Example usage (hypothetical C library and function) local my_lib = package.loadlib("/path/to/mylib.so", "luaopen_mylib_function") if my_lib then -- Use the loaded function end ``` ### Response #### Success Response (200) - **function** (C function) - The loaded C function. - **nil** - If `funcname` is "*" and the library links successfully. #### Response Example ```lua -- Successful load of a specific function function: ... -- Successful linking without loading a specific function -- (no return value, implies success) ``` ### Notes - This function is platform-dependent and not standard ISO C. - It is inherently insecure as it allows calling arbitrary functions in any readable dynamic library. ``` -------------------------------- ### Lua Float Constants Source: https://lua.org/manual/5.5/manual Examples of valid float constants in Lua. These include decimal floats with optional exponents and hexadecimal floats with optional binary exponents. ```lua 3.0 3.1416 314.16e-2 0.31416E1 34e1 0x0.1E 0xA23p-4 0X1.921FB54442D18P+1 ``` -------------------------------- ### package.config Source: https://lua.org/manual/5.5/manual Configuration string for packages. ```APIDOC ## package.config ### Description A string describing compile-time configurations for packages. It contains five lines: 1. Directory separator (default: '\' on Windows, '/' otherwise). 2. Path template separator (default: ';'). 3. Substitution point marker in templates (default: '?'). 4. String replaced by the executable's directory on Windows (default: '!'). 5. Marker to ignore text after it when building `luaopen_` function names (default: '-') ### Method GET ### Endpoint `/package/config` ### Response #### Success Response (200) - **config_string** (string) - The package configuration string. ``` -------------------------------- ### Get Hook Settings - Lua Source: https://lua.org/manual/5.5/manual Retrieves the current hook function, mask, and count for a given thread. Returns 'fail' if no hook is active. This is used in conjunction with debug.sethook. ```lua local hookFunc, hookMask, hookCount = debug.gethook() if hookFunc then print("Hook is active") else print("No active hook") end ``` -------------------------------- ### Lua Syntactic Sugar for Function Definitions Source: https://lua.org/manual/5.5/manual Illustrates syntactic sugar for defining functions, including regular, local, global, and method-style functions. ```lua stat ::= function funcname funcbody stat ::= local function Name funcbody stat ::= global function Name funcbody funcname ::= Name { . Name } [ : Name ] ``` -------------------------------- ### package.cpath Source: https://lua.org/manual/5.5/manual Path for searching C loaders. ```APIDOC ## package.cpath ### Description A string representing the path used by `require` to search for C loaders. It's initialized using environment variables `LUA_CPATH_5_5`, `LUA_CPATH`, or a default path from `luaconf.h`. ### Method GET ### Endpoint `/package/cpath` ### Response #### Success Response (200) - **cpath** (string) - The C path string. ``` -------------------------------- ### Lua C API: Get Absolute Index Source: https://lua.org/manual/5.5/manual Converts an acceptable index to an absolute index, which is independent of the stack size. This is useful for reliably accessing stack elements. ```c int lua_absindex (lua_State *L, int idx); ``` -------------------------------- ### Load and Execute Lua File (luaL_dofile) Source: https://lua.org/manual/5.5/manual Loads and executes a Lua file. It's a macro that combines `luaL_loadfile` and `lua_pcall`. Returns 0 on success and 1 on error (excluding out-of-memory errors). Useful for running external Lua scripts. ```c int luaL_dofile (lua_State *L, const char *filename); ``` ```c #define luaL_dofile(L, filename) \ (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) ``` -------------------------------- ### Get Function Information - Lua Source: https://lua.org/manual/5.5/manual Returns a table containing information about a function. This can be the function itself or a level in the call stack. The 'what' parameter controls which fields are included in the returned table. ```lua local info = debug.getinfo(1, "n") -- Get name of the calling function print(info.name) ``` ```lua local printInfo = debug.getinfo(print) -- Get all info about the print function print(printInfo.what) ``` -------------------------------- ### Table Creation with Preallocation in Lua Source: https://lua.org/manual/5.5/manual Creates a new, empty table with preallocated memory for sequence and record parts. This can improve performance and memory usage when the approximate size of the table is known beforehand. ```lua local new_table = table.create(10, 5) -- Preallocate for 10 sequence elements and 5 record elements print(type(new_table)) -- Output: table ``` -------------------------------- ### Get Metatable by Name (luaL_getmetatable) Source: https://lua.org/manual/5.5/manual Pushes the metatable associated with a given name from the Lua registry onto the stack. Returns the type of the pushed value, or `LUA_TNIL` if no metatable is found. ```c int luaL_getmetatable (lua_State *L, const char *tname); ``` -------------------------------- ### Get Lua Type Name (lua_typename) Source: https://lua.org/manual/5.5/manual Returns the string name of a Lua type, given its integer code. The input `tp` must be a valid type code returned by lua_type. ```c const char *lua_typename (lua_State *L, int tp); ``` -------------------------------- ### Loading Standard Libraries Source: https://lua.org/manual/5.5/manual Functions to load all or selected standard Lua libraries into a C state. ```APIDOC ## `luaL_openlibs` ### Description Opens all standard Lua libraries into the given state. ### Method `void luaL_openlibs (lua_State *L);` ### Parameters - **L** (`lua_State *`) - The Lua state to open libraries into. ### Request Example ```c luaL_openlibs(L); ``` ### Response - **None** ## `luaL_openselectedlibs` ### Description Opens (loads) and preloads selected standard libraries into the state `L`. Preloading adds the library loader to `package.preload`. ### Method `void luaL_openselectedlibs (lua_State *L, int load, int preload); ` ### Parameters - **L** (`lua_State *`) - The Lua state to open libraries into. - **load** (`int`) - A bitmask indicating which libraries to load. - **preload** (`int`) - A bitmask indicating which libraries to preload. ### Constants for `load` and `preload` masks: - **`LUA_GLIBK`**: the basic library. - **`LUA_LOADLIBK`**: the package library. - **`LUA_COLIBK`**: the coroutine library. - **`LUA_STRLIBK`**: the string library. - **`LUA_UTF8LIBK`**: the UTF-8 library. - **`LUA_TABLIBK`**: the table library. - **`LUA_MATHLIBK`**: the mathematical library. - **`LUA_IOLIBK`**: the I/O library. - **`LUA_OSLIBK`**: the operating system library. - **`LUA_DBLIBK`**: the debug library. ### Request Example ```c // Load basic and math libraries, preload string library luaL_openselectedlibs(L, LUA_GLIBK | LUA_MATHLIBK, LUA_STRLIBK); ``` ### Response - **None** ``` -------------------------------- ### Lua Length Operator Example (String and Table) Source: https://lua.org/manual/5.5/manual Shows the usage of the Lua length operator '#'. For strings, it returns the number of bytes. For tables, it returns a border, which corresponds to the intuitive length for sequences. ```lua -- String length local myString = "Lua" print(#myString) -- Output: 3 -- Table length (sequence) local myTable = {10, 20, 30} print(#myTable) -- Output: 3 -- Table length (non-sequence) local complexTable = {10, 20, nil, 40} print(#complexTable) -- Output can be 2 or 4 depending on implementation. ``` -------------------------------- ### Create New Table - lua_newtable Source: https://lua.org/manual/5.5/manual Creates a new, empty table and pushes it onto the Lua stack. This function is a convenience wrapper for `lua_createtable(L, 0, 0)`, meaning it initializes a table with no pre-allocated array or hash parts. ```c void lua_newtable (lua_State *L); ``` -------------------------------- ### Get Length of Lua Value (luaL_len) Source: https://lua.org/manual/5.5/manual Returns the length of a Lua value at a given stack index, equivalent to the Lua '#' operator. Raises an error if the result is not an integer, which can occur via metamethods. ```c lua_Integer luaL_len (lua_State *L, int index); ``` -------------------------------- ### Open Selected Standard Lua Libraries in C Source: https://lua.org/manual/5.5/manual The `luaL_openselectedlibs` function allows C host programs to open or preload specific standard Lua libraries. It uses bitmasks to select which libraries to load and which to add to `package.preload` for later `require` calls. This provides fine-grained control over library availability. ```c void luaL_openselectedlibs (lua_State *L, int load, int preload); ``` -------------------------------- ### Create New Lua State with luaL_newstate Source: https://lua.org/manual/5.5/manual Creates and initializes a new Lua state. It uses a default allocator (`luaL_alloc`) and a seed from `luaL_makeseed(NULL)`. It also sets default warning and panic functions that print to standard error. Returns NULL on memory allocation failure. ```c lua_State *luaL_newstate (void); ``` -------------------------------- ### Handling Yields with Continuation Functions Source: https://lua.org/manual/5.5/manual This section details how to use continuation functions with `lua_yieldk`, `lua_callk`, and `lua_pcallk` to manage C function execution when Lua code yields. ```APIDOC ## Using Continuation Functions for Yielding ### Description When a C function called from Lua needs to yield, it cannot return directly to the original C caller if its stack frame was destroyed by `longjmp`. To handle this, Lua provides `lua_yieldk`, `lua_callk`, and `lua_pcallk`, which accept a continuation function (`lua_KFunction`) to resume execution. ### Key Functions - **`lua_yieldk`**: Allows yielding with a continuation function. - **`lua_callk`**: Calls a Lua function, allowing it to yield and resuming with a continuation. - **`lua_pcallk`**: Calls a Lua function in protected mode, allowing it to yield and resuming with a continuation. ### Continuation Function (`lua_KFunction`) ```c typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx); ``` - **`L`**: The Lua state. - **`status`**: The status of the call (e.g., `LUA_YIELD`, `LUA_OK`). - **`ctx`**: A context value passed from the original function. The continuation function should perform the work that the original function would have done after the callee function returns. Lua calls the continuation function when the thread resumes after a yield or in case of errors (for `lua_pcallk`). ### Example Scenario Consider an original function calling `lua_pcall`: ```c int original_function (lua_State *L) { /* code 1 */ status = lua_pcall(L, n, m, h); /* code 2 */ } ``` To allow yielding, rewrite the function using `lua_pcallk` and a continuation function `k`: ```c int k (lua_State *L, int status, lua_KContext ctx) { /* code 2 - continuation logic */ return status; /* Or appropriate return */ } int original_function (lua_State *L) { /* code 1 */ /* Call lua_pcallk, passing the continuation function 'k' */ return lua_pcallk(L, n, m, h, ctx, k); } ``` When `lua_pcallk` is used, if the called Lua code yields, Lua will not return to `original_function` directly. Instead, it will eventually call the continuation function `k` with `status` set to `LUA_YIELD` after the thread resumes. If the Lua code finishes normally without yielding, `lua_pcallk` returns normally, and the continuation function `k` is not called by Lua (though you can explicitly call it if desired). ### Important Notes - `lua_yieldk` and `lua_callk` do not handle errors; continuations are primarily for resuming after a yield. - When using `lua_callk`, the continuation should typically be called with `LUA_OK` status if the called function returns normally. - The continuation function receives the same Lua stack and upvalues as the original function at the point of interruption. ``` -------------------------------- ### Get or Create Subtable (luaL_getsubtable) Source: https://lua.org/manual/5.5/manual Ensures that a nested field is a table, creating it if necessary. It pushes the subtable onto the stack and returns whether it was existing or newly created. Useful for managing table structures. ```c int luaL_getsubtable (lua_State *L, int idx, const char *fname); ``` -------------------------------- ### Get Temporary Filename - Lua Source: https://lua.org/manual/5.5/manual Returns a string containing a filename suitable for temporary files. The file must be explicitly opened and removed by the user. On POSIX systems, a file is created to prevent security risks. ```lua local tempFileName = os.tmpname() print("Temporary file name: " .. tempFileName) -- Remember to open and remove the file explicitly ``` -------------------------------- ### string.dump Source: https://lua.org/manual/5.5/manual Returns a binary representation of a given Lua function. ```APIDOC ## `string.dump (function [, strip])` ### Description Returns a string containing a binary representation (_binary chunk_) of the given function, so that a later `load` on this string returns a copy of the function (but with new upvalues). If `strip` is a true value, the binary representation may not include all debug information about the function, to save space. Functions with upvalues have only their number of upvalues saved. When (re)loaded, those upvalues receive fresh instances. ### Method (Implicitly a function call, not a typical HTTP method) ### Endpoint (N/A - this is a library function) ### Parameters #### Path Parameters (N/A) #### Query Parameters (N/A) #### Request Body (N/A) ### Request Example (N/A - this is a function call, not a request body) ### Response #### Success Response - **string** - A binary representation of the function. #### Response Example (N/A - function return values vary) ``` -------------------------------- ### Load and Execute Lua String (luaL_dostring) Source: https://lua.org/manual/5.5/manual Loads and executes a Lua string. Similar to `luaL_dofile`, this macro uses `luaL_loadstring` and `lua_pcall`. It returns 0 for success and 1 for errors. Ideal for executing Lua code dynamically from C. ```c int luaL_dostring (lua_State *L, const char *str); ``` ```c #define luaL_dostring(L, str) \ (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) ``` -------------------------------- ### Get Current Local Time - Lua Source: https://lua.org/manual/5.5/manual Retrieves the current local time as a numerical value. The exact meaning of this value depends on the system, often representing seconds since an epoch. It can be used with os.date and os.difftime. ```lua local currentTime = os.time() print(currentTime) ``` -------------------------------- ### Get Metatable Field with Lua C API (luaL_getmetafield) Source: https://lua.org/manual/5.5/manual Retrieves a field from the metatable of a Lua object. It pushes the field onto the stack and returns its type. Returns `LUA_TNIL` if the object has no metatable or the field is absent. ```c int luaL_getmetafield (lua_State *L, int obj, const char *e); ``` -------------------------------- ### Lua C API: Generate Stack Traceback with luaL_traceback Source: https://lua.org/manual/5.5/manual Creates and pushes a formatted stack traceback onto the Lua stack. It can prepend an optional message and start the traceback from a specified level, useful for error reporting. ```c void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level); ``` -------------------------------- ### Using lua_pcallk for Safe Yielding in C Source: https://lua.org/manual/5.5/manual Demonstrates the correct usage of lua_pcallk in a C function to allow Lua code to yield safely. This involves passing a continuation function (k) and a context (ctx2) to lua_pcallk, ensuring that execution can resume correctly after a yield. ```c int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); } ```