### Install LuaJIT (Native) Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/install.html Installs LuaJIT to the default location (/usr/local) which requires root privileges. Alternatively, you can specify a custom installation prefix, which must match the prefix used during the build. ```makefile sudo make install make install PREFIX=/home/myself/lj2 ``` -------------------------------- ### Lua string.gsub Example with Multiple Matches Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Demonstrates the behavior of string.gsub with patterns that can match empty strings, highlighting how Lua avoids immediate re-matching at the same position. ```lua string.gsub("abc", "()a*()", print) -- Expected output: -- 1 2 -- 3 3 -- 4 4 ``` -------------------------------- ### Lua Memory Allocation Function Example (C) Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Provides a basic implementation of the `lua_Alloc` function type, which is used for memory allocation within Lua states. This example mimics `realloc` behavior and handles zero-size allocations by calling `free`. ```c static void *l_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); } ``` -------------------------------- ### Execute System Processes with io.popen Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Starts a system process and returns a file handle for inter-process communication. This allows reading from or writing to external programs. ```lua -- Open a process to read its output local handle = io.popen("ls -l", "r") local result = handle:read("*a") handle:close() ``` -------------------------------- ### Cross-compile for ARM64 Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/install.html This command shows the basic setup for cross-compiling LuaJIT for the ARM64 architecture. It specifies the cross-compilation prefix. ```bash make CROSS=aarch64-linux- ``` -------------------------------- ### Initialize and Use Lua String Buffer Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Demonstrates the pattern for initializing and using a `luaL_Buffer` to build Lua strings incrementally. It covers initialization, adding string pieces, and finalizing the string. It also shows an alternative for preallocating space if the final size is known. ```c luaL_Buffer b; luaL_buffinit(L, &b); // Add string pieces using luaL_add* functions luaL_addstring(&b, "Hello, "); luaL_addstring(&b, "World!"); luaL_pushresult(&b); // Preallocation example luaL_Buffer b2; size_t sz = 50; char *buffer = luaL_buffinitsize(L, &b2, sz); // Copy string into buffer memcpy(buffer, "Preallocated string", 19); luaL_pushresultsize(&b2, 19); ``` -------------------------------- ### Traverse Lua Table with lua_next Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Demonstrates how to iterate over a Lua table using the `lua_next` function. It pushes a nil key to start, then repeatedly calls `lua_next` to get key-value pairs. The example highlights how to access the key and value, and importantly, how to manage the stack by popping the value after processing. ```c /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1); } ``` -------------------------------- ### Lua Integer Constants Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Examples of valid integer constants in Lua. These include decimal integers and hexadecimal integers, which must start with '0x' or '0X'. ```lua 3 ``` ```lua 345 ``` ```lua 0xff ``` ```lua 0xBEBADA ``` -------------------------------- ### Access zlib compression library from Lua Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/ext_ffi_tutorial.html This snippet shows how to load the zlib shared library and define C function signatures for compression and uncompression using LuaJIT's FFI. It includes convenience wrapper functions to compress and uncompress strings. ```lua local ffi = require("ffi") ffi.cdef([ unsigned long compressBound(unsigned long sourceLen); int compress2(uint8_t *dest, unsigned long *destLen, const uint8_t *source, unsigned long sourceLen, int level); int uncompress(uint8_t *dest, unsigned long *destLen, const uint8_t *source, unsigned long sourceLen); ]]) local zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z") local function compress(txt) local n = zlib.compressBound(#txt) local buf = ffi.new("uint8_t[?]", n) local buflen = ffi.new("unsigned long[1]", n) local res = zlib.compress2(buf, buflen, txt, #txt, 9) assert(res == 0) return ffi.string(buf, buflen[0]) end local function uncompress(comp, n) local buf = ffi.new("uint8_t[?]", n) local buflen = ffi.new("unsigned long[1]", n) local res = zlib.uncompress(buf, buflen, comp, #comp) assert(res == 0) return ffi.string(buf, buflen[0]) end -- Simple test code. local txt = string.rep("abcd", 1000) print("Uncompressed size: ", #txt) local c = compress(txt) print("Compressed size: ", #c) local txt2 = uncompress(c, #txt) assert(txt2 == txt) ``` -------------------------------- ### Registering and Using Class Constructors Source: https://github.com/kunitoki/luabridge3/blob/master/Manual.md Shows how to register C++ class constructors with specific signatures in LuaBridge3 and how to instantiate those classes within the Lua environment. ```cpp struct A { A (); A (std::string_view a); A (std::string_view a, int b); }; struct B { explicit B (const char* s, int nChars); }; luabridge::getGlobalNamespace (L) .beginNamespace ("test") .beginClass ("A") .addConstructor () .endClass () .beginClass ("B") .addConstructor () .endClass () .endNamespace (); ``` ```lua a = test.A () -- Create a new A. b = test.B ("hello", 5) -- Create a new B. b = test.B () -- Error: expected string in argument 1 ``` -------------------------------- ### Lua Assignment Example: Ambiguity Avoidance Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Shows the recommended practice in Lua to precede statements that start with an opening parenthesis with a semicolon to avoid grammatical ambiguity with function calls. ```lua ;(print or io.write)('done') ``` -------------------------------- ### LuaBridge Stack Specialization for juce::String in C++ Source: https://github.com/kunitoki/luabridge3/blob/master/Manual.md Provides an example C++ specialization of the `luabridge::Stack<>` template for the `juce::String` type. This demonstrates how to make a user-defined type convertible by implementing the `push` and `get` methods for handling string conversions between C++ and Lua. ```cpp namespace luabridge { template <> struct Stack { static Result push (lua_State* L, const juce::String& s) { lua_pushstring (L, s.toUTF8 ()); return {}; } static TypeResult get (lua_State* L, int index) { if (lua_type (L, index) != LUA_TSTRING) return makeErrorCode (ErrorCode::InvalidTypeCast); ``` -------------------------------- ### Demonstrate Table Constructor Syntax and Initialization Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html This snippet illustrates how Lua table constructors initialize fields using explicit keys, named keys, and implicit integer indexing. It demonstrates how various field formats are translated into table assignments. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } -- Equivalent to: do local t = {} t[f(1)] = g t[1] = "x" t[2] = "y" t.x = 1 t[3] = f(x) t[30] = 23 t[4] = 45 a = t end ``` -------------------------------- ### Get Local Variable Information with lua_getlocal Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.1.5/doc/manual.html Retrieves information about a local variable within a given activation record. It pushes the variable's value onto the Lua stack and returns the variable's name. The index 'n' specifies which local variable to retrieve, starting from 1. ```c const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n); ``` -------------------------------- ### Initialize cdata objects with ffi.new Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/ext_ffi_semantics.html Shows basic initialization patterns for C structures, unions, and arrays using Lua tables or default zero-initialization. ```lua local ffi = require("ffi") ffi.cdef[[ struct foo { int a, b; }; union bar { int i; double d; }; struct nested { int x; struct foo y; }; ]] -- Initialize an array of 3 integers with zeros ffi.new("int[3]", {}) ``` -------------------------------- ### Handle Variadic Arguments in Lua Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.1.5/doc/manual.html Shows how to define functions that accept a variable number of arguments using the '...' syntax. ```lua function g(a, b, ...) -- '...' collects extra arguments end -- Example calls: -- g(3, 4, 5, 8) -> a=3, b=4, ... contains 5 and 8 ``` -------------------------------- ### Install LuaJIT Components (CMake) Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/CMakeLists.txt Installs LuaJIT-related files, including bytecode and disassembler scripts, from the source and binary directories to the specified destination within the Lua installation path. ```cmake INSTALL(FILES src/jit/bc.lua src/jit/v.lua src/jit/dump.lua src/jit/dis_x86.lua src/jit/dis_x64.lua src/jit/dis_arm.lua src/jit/dis_ppc.lua src/jit/dis_mips.lua src/jit/dis_mipsel.lua src/jit/bcsave.lua ${CMAKE_CURRENT_BINARY_DIR}/vmdef.lua src/jit/p.lua src/jit/zone.lua src/jit/dis_arm64.lua src/jit/dis_arm64be.lua src/jit/dis_mips64.lua src/jit/dis_mips64el.lua DESTINATION "${Lua_INSTALL_LUA_PATH_SUBDIR}/jit") ``` -------------------------------- ### Lua Capture Group Example Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Illustrates how nested parentheses in Lua patterns create capture groups, storing specific parts of the matched string for later use. The example shows numbering of captures based on their opening parentheses. ```lua -- Pattern: "(a*(.)%w(%s*))" -- Capture 1: "a*(.)%w(%s*)" -- Capture 2: "." -- Capture 3: "%s*" -- Example with "()aa()" on "flaaap" -- Capture 1: position 3 -- Capture 2: position 5 ``` -------------------------------- ### Lua Comments Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Shows the syntax for both short and long comments in Lua. Short comments start with '--' and extend to the end of the line. Long comments start with '--[[' and end with the corresponding ']]', useful for temporarily disabling code blocks. ```lua -- This is a short comment. --[[ This is a long comment. It can span multiple lines. ]] ``` -------------------------------- ### Initialize cdata arrays, structs, and unions Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/ext_ffi_semantics.html Demonstrates how to use ffi.new to allocate and initialize various C data types including arrays, structs, unions, and nested structures. It highlights how initializers map to memory fields and how excess initializers are handled. ```Lua -- Array initialization ffi.new("int[3]", {1}) -- 1, 1, 1 ffi.new("int[3]", {1, 2, 3}) -- 1, 2, 3 -- Struct initialization ffi.new("struct foo", {1, 2}) -- a = 1, b = 2 ffi.new("struct foo", {b = 2}) -- a = 0, b = 2 -- Union initialization ffi.new("union bar", {d = 2}) -- i = ?, d = 2.0 -- Nested struct initialization ffi.new("struct nested", {x = 1, y = {2, 3}}) ``` -------------------------------- ### Constructing Tables with Lua Syntax Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.1.5/doc/manual.html Demonstrates the use of table constructors to initialize fields using explicit keys, named keys, and implicit numerical indices. It shows how various field formats map to internal table assignments. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } -- Equivalent logic: do local t = {} t[f(1)] = g t[1] = "x" t[2] = "y" t.x = 1 t[3] = f(x) t[30] = 23 t[4] = 45 a = t end ``` -------------------------------- ### Lua Comments: Short and Long Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Illustrates the syntax for both short and long comments in Lua. Short comments start with '--' and extend to the end of the line. Long comments start with '--[[' and end with ']]', and are often used for temporarily disabling code blocks. ```lua -- This is a short comment ``` ```lua --[[ This is a long comment that can span multiple lines. It is often used to disable code blocks. ]]-- ``` -------------------------------- ### Basic Library: dofile Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Opens and executes a file as a Lua chunk. ```APIDOC ## dofile ([filename]) ### Description Opens the named file and executes its contents as a Lua chunk. If no filename is provided, it reads from stdin. ### Parameters #### Query Parameters - **filename** (string) - Optional - Path to the Lua file. ### Response - **Success** (list) - Returns all values returned by the executed chunk. ``` -------------------------------- ### Implementing Lua C API Continuations Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Demonstrates the transition from a standard C function to a continuation-ready implementation using lua_pcallk. The continuation function 'k' handles post-yield or post-error logic, while the original function manages the initial call and context passing. ```C /* Continuation function definition */ int k (lua_State *L, int status, lua_KContext ctx) { /* code 2: logic to execute after yield/error */ return 0; } /* Original function using continuation */ int original_function (lua_State *L) { /* code 1: initial setup */ return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1); } ``` -------------------------------- ### Coroutine Management: lua_resume Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Starts or resumes a Lua coroutine thread. ```APIDOC ## POST lua_resume ### Description Starts and resumes a coroutine in the given thread L. It handles the transition between yielding and resuming execution. ### Method C Function ### Parameters - **L** (lua_State*) - Required - The thread to resume. - **from** (lua_State*) - Required - The coroutine that is resuming L (can be NULL). - **nargs** (int) - Required - Number of arguments to pass. ### Response - **Return** (int) - LUA_YIELD if yielded, LUA_OK if finished, or an error code. ``` -------------------------------- ### Build LuaJIT (Native) Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/install.html Builds a native LuaJIT binary for the host operating system using GNU Make. Modules are searched under /usr/local by default. You can specify an alternative installation prefix. ```makefile make make PREFIX=/home/myself/lj2 ``` -------------------------------- ### GET os.tmpname Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Generates a unique filename suitable for a temporary file. ```APIDOC ## GET os.tmpname ### Description Returns a string containing a file name that can be used for a temporary file. The file must be manually opened and removed. ### Method GET ### Endpoint os.tmpname() ### Response #### Success Response (200) - **filename** (string) - A path string for a temporary file. ### Response Example { "filename": "/tmp/lua_abc123" } ``` -------------------------------- ### Lua Coroutine Example using coroutine.create Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Demonstrates the creation and execution of Lua coroutines using `coroutine.create` and `coroutine.resume`. It shows how to pass arguments and handle return values between the main thread and the coroutine body. Errors in coroutines are propagated to the caller. ```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 Length Operator Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Function to get the length of a Lua value. ```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 N/A (C function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (void) - No return value. The length is pushed onto the stack. #### Response Example N/A ``` -------------------------------- ### Find Substring or Pattern in Lua String Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html The `string.find` function searches for the first occurrence of a pattern within a string. It returns the start and end indices of the match, or nil if no match is found. Optional arguments control the starting position and disable pattern matching for plain substring searches. ```lua local s = "hello world" local start, end_pos = string.find(s, "world") print(start, end_pos) -- Output: 7 11 local plain_search = string.find(s, "o w", 1, true) print(plain_search) -- Output: 5 ``` -------------------------------- ### Load FFI Library in LuaJIT Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/ext_ffi_tutorial.html This snippet shows the standard way to load and initialize the FFI library in LuaJIT. It uses `require('ffi')` to get the FFI module and assigns it to a local variable `ffi`. This ensures the library is loaded only once and avoids polluting the global namespace. ```lua local ffi = require("ffi") ``` -------------------------------- ### Create New Library with Functions (C) Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Creates a new table and registers functions from the provided luaL_Reg list 'l' into it. Implemented as a macro combining luaL_newlibtable and luaL_setfuncs. ```c void luaL_newlib (lua_State *L, const luaL_Reg *l); ``` -------------------------------- ### string.sub Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Extracts a substring from a given string based on start and end indices. ```APIDOC ## POST /string/sub ### Description Returns the substring of `s` that starts at `i` and continues until `j`; `i` and `j` can be negative. If `j` is absent, then it is assumed to be equal to -1. ### Method POST ### Endpoint /string/sub ### Parameters #### Request Body - **s** (string) - Required - The input string. - **i** (number) - Required - The starting index. - **j** (number) - Optional - The ending index (default is -1). ### Request Example ```json { "s": "hello world", "i": 7, "j": 11 } ``` ### Response #### Success Response (200) - **result** (string) - The extracted substring. #### Response Example ```json { "result": "world" } ``` ``` -------------------------------- ### string.sub Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html 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 `i` and continues until `j`; `i` and `j` can be negative. If `j` is absent, then it is assumed to be equal to -1 (which is the same as the string length). Negative indices are translated, and `i` and `j` are corrected to be within the string bounds. If `i` becomes greater than `j` after corrections, an empty string is returned. ### Method `string.sub` ### Parameters #### Path Parameters - **s** (string) - Required - The string to extract from. - **i** (number) - Required - The starting index (can be negative). - **j** (number) - Optional - The ending index (can be negative). Defaults to -1 (end of string). ### Request Example ```lua -- Example usage (conceptual) local sub1 = string.sub("abcdef", 2, 4) print(sub1) -- Output: "bcd" local sub2 = string.sub("abcdef", -3) print(sub2) -- Output: "def" local sub3 = string.sub("abcdef", 1, 2) print(sub3) -- Output: "ab" ``` ### Response #### Success Response - **substring** (string) - The extracted substring. ``` -------------------------------- ### Cross-compile for PPC Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/install.html This command demonstrates cross-compiling LuaJIT for the PowerPC (PPC) architecture. It includes the host compiler and the cross-compilation prefix. ```bash make HOST_CC="gcc -m32" CROSS=powerpc-linux-gnu- ``` -------------------------------- ### GET debug.getinfo Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Retrieves detailed information about a specific function or stack level. ```APIDOC ## GET debug.getinfo ### Description Returns a table containing information about a function or a stack level. ### Method GET ### Endpoint debug.getinfo([thread,] f [, what]) ### Parameters #### Query Parameters - **thread** (thread) - Optional - The thread to operate on. - **f** (function/number) - Required - The function or stack level to inspect. - **what** (string) - Optional - A string specifying which fields to retrieve. ### Response #### Success Response (200) - **info** (table) - A table containing metadata about the function. ### Response Example { "name": "my_function", "source": "@script.lua", "linedefined": 10 } ``` -------------------------------- ### Manage Lua libraries and tables Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Utilities for creating tables for library registration and initializing standard Lua libraries. These functions facilitate the modular extension of the Lua environment. ```C void luaL_newlib(lua_State *L, const luaL_Reg l[]); void luaL_newlibtable(lua_State *L, const luaL_Reg l[]); void luaL_openlibs(lua_State *L); ``` -------------------------------- ### POST package.loadlib Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Dynamically links the host program with a specified C library and optionally retrieves a function from it. ```APIDOC ## POST package.loadlib ### Description Dynamically links the host program with the C library `libname`. This function is low-level and bypasses the standard package/module system. ### Method POST ### Endpoint package.loadlib(libname, funcname) ### Parameters #### Request Body - **libname** (string) - Required - The complete file name of the C library, including path and extension. - **funcname** (string) - Required - The name of the function to export, or "*" to only link the library. ### Response #### Success Response (200) - **function** (lua_CFunction) - The C function retrieved from the library. ### Response Example { "status": "success", "data": "function_pointer" } ``` -------------------------------- ### Control Coroutine Execution Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Functions to start, resume, and reset coroutines within the Lua state. ```C int lua_resetthread(lua_State *L); int lua_resume(lua_State *L, lua_State *from, int nargs, int *nresults); ``` -------------------------------- ### Start and Resume Coroutines with lua_resume Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.1.5/doc/manual.html The `lua_resume` function starts and resumes coroutines. It takes the Lua state and the number of arguments to pass to the coroutine. It returns status codes indicating whether the coroutine yielded, finished successfully, or encountered an error. To restart a coroutine, values returned from a previous yield are pushed onto the stack and then `lua_resume` is called. ```c int lua_resume (lua_State *L, int narg); // Starts and resumes a coroutine in a given thread. // To start a coroutine, you first create a new thread (see lua_newthread); // then you push onto its stack the main function plus any arguments; // then you call lua_resume, with narg being the number of arguments. // This call returns when the coroutine suspends or finishes its execution. // When it returns, the stack contains all values passed to lua_yield, or all values returned by the body function. // lua_resume returns LUA_YIELD if the coroutine yields, 0 if the coroutine finishes its execution without errors, or an error code in case of errors (see lua_pcall). // In case of errors, the stack is not unwound, so you can use the debug API over it. // The error message is on the top of the stack. // To restart a coroutine, you put on its stack only the values to be passed as results from yield, and then call lua_resume. ``` -------------------------------- ### dofile Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Opens and executes a file as a Lua chunk. ```APIDOC ## dofile ([filename]) ### Description Opens the named file and executes its contents as a Lua chunk. If no filename is provided, it reads from stdin. ### Method FUNCTION ### Parameters #### Query Parameters - **filename** (string) - Optional - Path to the Lua file to execute. ### Response #### Success Response (200) - **values** (any) - Returns all values returned by the executed chunk. ``` -------------------------------- ### Manage file I/O operations in Lua Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Examples of standard I/O operations including opening files, reading lines, and managing default file descriptors. These functions provide interfaces for both implicit and explicit file handling. ```lua local file = io.open("test.txt", "r") if file then for line in file:lines() do print(line) end file:close() end io.write("Writing to default output") io.flush() ``` -------------------------------- ### file:seek Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Sets and gets the file position. Returns the final file position or 'fail' on error. ```APIDOC ## file:seek ### Description Sets and gets the file position. Returns the final file position in bytes from the beginning of the file, or 'fail' on error. ### Method `file:seek([whence [, offset]])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - whence - **`"set`"**: Base is position 0 (beginning of the file). - **`"cur`"**: Base is the current position (default). - **`"end`"**: Base is the end of the file. ### Parameters - offset - **_number_**: The offset from the base position (default is 0). ### Request Example ```lua local current_pos = file:seek() -- Get current position file:seek('set', 100) -- Move to byte 100 from the beginning local end_pos = file:seek('end') -- Move to the end and get size ``` ### Response #### Success Response - **position** (number) - The final file position, measured in bytes from the beginning of the file. #### Response Example ```lua local pos = file:seek('set', 50) print(pos) -- Output: 50.0 ``` ``` -------------------------------- ### GET package.searchers Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Retrieves the table of searcher functions used by the require system to locate and load modules. ```APIDOC ## GET package.searchers ### Description Returns the table of searcher functions. Each function is called in order by require to find a module loader. ### Method GET ### Endpoint package.searchers ### Response #### Success Response (200) - **searchers** (table) - A list of functions used for module resolution. ### Response Example { "searchers": ["preload_searcher", "lua_path_searcher", "c_path_searcher", "all_in_one_searcher"] } ``` -------------------------------- ### Handle C Functions with Output Arguments Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/LuaJIT.2.1/doc/ext_ffi_tutorial.html Shows how to pass a Lua-allocated buffer to a C function expecting a pointer to an output variable. The buffer is created using ffi.new and accessed via index. ```C void foo(int *inoutlen); int len = x; foo(&len); y = len; ``` ```Lua local len = ffi.new("int[1]", x) foo(len) y = len[0] ``` -------------------------------- ### GET package.path Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Retrieves the current search path used by the require function to locate Lua loaders. ```APIDOC ## GET package.path ### Description Returns the path string used by the require function to search for Lua modules. Initialized from environment variables or default configuration. ### Method GET ### Endpoint package.path ### Response #### Success Response (200) - **path** (string) - The semicolon-separated search path. ### Response Example { "path": "./?.lua;/usr/local/share/lua/5.3/?.lua" } ``` -------------------------------- ### Lua Multiple Assignment Example Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Demonstrates Lua's multiple assignment capabilities, including swapping variables and cyclic permutation of values. It highlights how expressions are evaluated before assignments occur. ```lua i = 3 i, a[i] = i+1, 20 x, y = y, x x, y, z = y, z, x ``` -------------------------------- ### GET os.time Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.4.6/doc/manual.html Returns the current time or a time representing a specific date and time provided via a table. ```APIDOC ## GET os.time ### Description Returns the current time as a number. If a table is provided, it returns the time representing the local date and time specified by that table. ### Method GET ### Endpoint os.time([table]) ### Parameters #### Query Parameters - **table** (table) - Optional - A table containing year, month, day, and optionally hour, min, sec, and isdst. ### Response #### Success Response (200) - **time** (number) - The number of seconds since the epoch or a system-specific time representation. ### Response Example { "time": 1672531200 } ``` -------------------------------- ### Get environment table with lua_getfenv Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.1.5/doc/manual.html Pushes the environment table of the value at the specified stack index onto the stack. ```C void lua_getfenv (lua_State *L, int index); ``` -------------------------------- ### Lua Table Constructor Syntax Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Demonstrates the syntax for creating Lua tables, initializing fields with various key-value pairs, and handling sequential numeric keys. It also covers the optional trailing separator. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } ``` ```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_createtable Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.3.6/doc/manual.html Creates a new empty table and pushes it onto the stack. ```APIDOC ## void lua_createtable(lua_State *L, int narr, int nrec) ### Description Creates a new empty table and pushes it onto the stack. Uses hints for preallocation. ### Parameters #### Request Body - **narr** (int) - Required - Hint for sequence elements. - **nrec** (int) - Required - Hint for non-sequence elements. ### Response - **void** - Pushes the new table onto the stack. ``` -------------------------------- ### Manage Expression Result Adjustment in Lua Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Examples of how function calls and varargs are adjusted based on their position in an expression list. ```Lua f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result a,b,c = f() -- f() is adjusted to 3 results return f() -- returns all results from f() {f()} -- creates a list with all results from f() ``` -------------------------------- ### Lua Function Call Syntax Source: https://github.com/kunitoki/luabridge3/blob/master/Tests/Lua/Lua.5.2.4/doc/manual.html Illustrates the basic syntax for calling functions in Lua, including how arguments are passed and how the 'call' metamethod is invoked if the prefixexp is not a function. It also covers method call syntax. ```lua functioncall ::= prefixexp args ``` ```lua functioncall ::= prefixexp ":" Name args ``` ```lua v:name(_args_) is syntactic sugar for v.name(v, _args_) ```