### HTTP Client Request Example Source: https://www.lua.org/wshop17/lua-http.html Demonstrates how to make an HTTP GET request using the lua-http client library and process the response. ```lua local http_request = require "http.request" local my_req = http_request.new_from_uri("http://httpbin.org/get") local headers, stream = assert(my_req:go()) for field, value in headers:each() do print(field, value) end local body = assert(stream:get_body_as_string()) print(body) ``` -------------------------------- ### String Handling Example Source: https://www.lua.org/pil/24.2.2.html Example demonstrating how to get a string from the stack and its length using `lua_tostring` and `lua_strlen`. ```APIDOC ## String Handling Example ```c const char *s = lua_tostring(L, -1); /* any Lua string */ size_t l = lua_strlen(L, -1); /* its length */ assert(s[l] == '\0'); assert(strlen(s) <= l); ``` ``` -------------------------------- ### Install Lua System-Wide Source: https://www.lua.org/work/diffu-lua-5.2.3-lua-5.2.4.txt Command to install Lua to the system's official directories. This typically requires administrator privileges. ```bash make install ``` -------------------------------- ### Complete Markov Chain Program - Setup and Table Building Source: https://www.lua.org/pil/10.2.html The complete Lua program for the Markov chain algorithm, including setup, word iteration, and building the state table. ```lua -- Markov Chain Program in Lua function allwords () local line = io.read() -- current line local pos = 1 -- current position in the line return function () -- iterator function while line do -- repeat while there are lines local s, e = string.find(line, "%w+", pos) if s then -- found a word? pos = e + 1 -- update next position return string.sub(line, s, e) -- return the word else line = io.read() -- word not found; try next line pos = 1 -- restart from first position end end return nil -- no more lines: end of traversal end end function prefix (w1, w2) return w1 .. ' ' .. w2 end local statetab function insert (index, value) if not statetab[index] then statetab[index] = {n=0} end table.insert(statetab[index], value) end local N = 2 local MAXGEN = 10000 local NOWORD = "\n" -- build table statetab = {} local w1, w2 = NOWORD, NOWORD for w in allwords() do insert(prefix(w1, w2), w) w1 = w2; w2 = w; end insert(prefix(w1, w2), NOWORD) ``` -------------------------------- ### Buffer Manipulation Examples Source: https://www.lua.org/notes/ltn003.html Demonstrates how to use the array_words and array_chars functions to populate buffers with different data types. Shows examples of writing numbers, strings, and other arrays into buffers. ```lua x,y = array(n),array(m) x:chars { [0] = "hello".."\0" } -- only 6 bytes taken up so far x:words { [2] = a_num, [3] = y } ``` -------------------------------- ### Install Primitive Tracer Hook Source: https://www.lua.org/pil/23.2.html Installs a hook to print the number of each new line the interpreter executes. This is a basic setup for line event monitoring. ```lua debug.sethook(print, "l") ``` -------------------------------- ### Array Access Example in Lua Source: https://www.lua.org/pil/28.4.html Demonstrates setting and getting values from a custom array type using bracket notation (`a[i]`) after metamethods have been configured. ```lua a = array.new(1000) a[10] = 3.4 -- setarray print(a[10]) -- getarray --> 3.4 ``` -------------------------------- ### Install Lua to a Custom Directory Source: https://www.lua.org/work/diffu-lua-5.2.3-lua-5.2.4.txt Command to install Lua to a specified directory using the INSTALL_TOP variable. Be mindful of absolute vs. relative paths. ```bash make install INSTALL_TOP=xxx ``` -------------------------------- ### Install Lua Locally Source: https://www.lua.org/work/diffu-lua-5.2.3-lua-5.2.4.txt Command to install Lua into a local directory named 'install'. This is useful for development without system-wide installation. ```bash make local ``` -------------------------------- ### Lua Object-Oriented Syntax Example Source: https://www.lua.org/pil/28.3.html Demonstrates the object-oriented syntax for interacting with a custom array type in Lua, including creating, setting, and getting elements, and retrieving the size. ```lua a = array.new(1000) print(a:size()) --> 1000 a:set(10, 3.4) print(a:get(10)) --> 3.4 ``` -------------------------------- ### Initialize Lua Array with Custom Start Index Source: https://www.lua.org/pil/11.1.html Demonstrates creating an array that starts at a negative index. Lua arrays can be indexed from any integer value. ```lua a = {} for i=-5, 5 do a[i] = 0 end ``` -------------------------------- ### Lua require Path Resolution Examples Source: https://www.lua.org/pil/8.1.html Shows how `require` resolves a virtual file name against a given path. The examples demonstrate the transformation of the virtual name into potential real file names. ```lua lili lili.lua c:\\windows\\lili /usr/local/lua/lili/lili.lua ``` -------------------------------- ### Lua Hook Setting Example Source: https://www.lua.org/bugs.html Demonstrates how to set line and return hooks in Lua with a count. This example is relevant to a bug where the count hook might be called without being set. ```c lua_sethook(L, my_hook, LUA_MASKLINE | LUA_MASKRET, 1); ``` -------------------------------- ### Install Custom Line Event Tracer Source: https://www.lua.org/pil/23.2.html Installs a custom trace function to log the source file and line number for each executed line. Requires the 'l' mask for line events. ```lua function trace (event, line) local s = debug.getinfo(2).short_src print(s .. ":" .. line) end debug.sethook(trace, "l") ``` -------------------------------- ### Lua Configuration File Example Source: https://www.lua.org/pil/25.html A simple Lua configuration file defining window width and height variables. ```lua -- configuration file for program `pp' -- define window size width = 200 height = 300 ``` -------------------------------- ### Matching a Digit at the Start of a String Source: https://www.lua.org/pil/20.2.html Demonstrates anchoring a pattern to the beginning of a string using '^'. This example checks if the string 's' starts with a digit. ```lua if string.find(s, "^%d") then ... ``` -------------------------------- ### Continuation Function Setup Source: https://www.lua.org/manual/5.5/manual.html Shows how to define a continuation function 'k' and modify the original function to call it after a lua_pcall. This prepares for yield handling. ```c int k (lua_State *L, int status, lua_KContext ctx) { ... /* code 2 */ } int original_function (lua_State *L) { ... /* code 1 */ return k(L, lua_pcall(L, n, m, h), ctx); } ``` -------------------------------- ### Initialize Package Paths Source: https://www.lua.org/work/diffu-lua-5.3.3-lua-5.3.4.txt Initializes package.cpath and package.path in a similar manner to how Lua handles them. ```c Lua initializes the C path package.cpath in the same way it initializes the Lua path package.path, ``` -------------------------------- ### Creating and Using a New Account Instance Source: https://www.lua.org/pil/16.1.html This example shows how to create a new account object 'a' using the 'Account:new' constructor and then call a method 'deposit' on it. This demonstrates the usage of the emulated class system. ```Lua a = Account:new{balance = 0} a:deposit(100.00) ``` -------------------------------- ### Opening the 'package' library Source: https://www.lua.org/source/5.5/loadlib.c.html The main entry point for the 'package' library, setting up its tables, paths, and functions. ```c LUAMOD_API int luaopen_package (lua_State *L) { luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ lua_pop(L, 1); /* will not use it now */ luaL_newlib(L, pk_funcs); /* create 'package' table */ createsearcherstable(L); /* set paths */ setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); /* store config information */ lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); lua_setfield(L, -2, "config"); /* set field 'loaded' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_setfield(L, -2, "loaded"); /* set field 'preload' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); lua_setfield(L, -2, "preload"); lua_pushglobaltable(L); lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ lua_pop(L, 1); /* pop global table */ return 1; /* return 'package' table */ } ``` -------------------------------- ### Lua Window Constructor and Prototype Setup Source: https://www.lua.org/pil/13.4.1.html Sets up a namespace, a prototype table with default window parameters, and a metatable for new window objects. This code is a prerequisite for using the __index metamethod for inheritance. ```lua -- create a namespace Window = {} -- create the prototype with default values Window.prototype = {x=0, y=0, width=100, height=100, } -- create a metatable Window.mt = {} -- declare the constructor function function Window.new (o) setmetatable(o, Window.mt) return o end ``` -------------------------------- ### Get Userdata Memory Block Address Source: https://www.lua.org/source/5.5/lobject.h.html Retrieves the starting address of the memory block allocated for a userdata. It uses `udatamemoffset` to find the correct position. ```c #define getudatamem(u) (cast_charp(u) + udatamemoffset((u)->nuvalue)) ``` -------------------------------- ### Lua Block Comment Example Source: https://www.lua.org/pil/1.3.html Demonstrates how to use block comments in Lua to comment out a section of code. Block comments start with --[[ and end with ]]. ```lua --[[ print(10) -- no action (comment) --]] ``` -------------------------------- ### Opening a C library after loading with loadlib Source: https://www.lua.org/pil/8.2.html This example demonstrates loading a C library using `loadlib` and then calling the returned function `f()` to actually open and initialize the library. It includes error handling with `assert` and shows an alternative path for Windows DLLs. ```Lua local path = "/usr/local/lua/lib/libluasocket.so" -- or path = "C:\\windows\\luasocket.dll" local f = assert(loadlib(path, "luaopen_socket")) f() -- actually open the library ``` -------------------------------- ### Create and Resume Coroutine Example Source: https://www.lua.org/manual/5.5/manual.html Demonstrates the creation of a coroutine using `coroutine.create` and its subsequent execution and yielding using `coroutine.resume`. Shows how arguments are passed and returned between the main thread and the coroutine. ```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")) ``` -------------------------------- ### Get Userdata Value (Lua API) Source: https://www.lua.org/source/5.5/lapi.c.html Retrieves a user value from a full userdata at a given stack index. User values are indexed starting from 1. ```c LUA_API int lua_getiuservalue (lua_State *L, int idx, int n) { TValue *o; int t; lua_lock(L); o = index2value(L, idx); api_check(L, ttisfulluserdata(o), "full userdata expected"); if (n <= 0 || n > uvalue(o)->nuvalue) { setnilvalue(s2v(L->top.p)); t = LUA_TNONE; } else { setobj2s(L, L->top.p, &uvalue(o)->uv[n - 1].uv); t = ttype(s2v(L->top.p)); } api_incr_top(L); lua_unlock(L); return t; } ``` -------------------------------- ### Lua Numeric for Loop Examples Source: https://www.lua.org/pil/4.3.4.html Illustrates basic usage of the numeric for loop with different start, end, and step values. The control variable is local to the loop. ```lua for i=1,f(x) do print(i) end for i=10,1,-1 do print(i) end ``` -------------------------------- ### Lua Configuration for Program Settings Source: https://www.lua.org/pil/25.1.html Example of a Lua configuration file defining window dimensions and background color components. ```lua -- configuration file for program `pp' width = 200 height = 300 background_red = 0.30 background_green = 0.10 background_blue = 0 ``` -------------------------------- ### Valid Lua Identifiers Source: https://www.lua.org/pil/1.3.html Examples of valid identifiers in Lua. Identifiers can include letters, digits, and underscores, but cannot start with a digit. Locale-dependent characters can also be used. ```lua i j i10 _ij aSomewhatLongName _INPUT ``` -------------------------------- ### Creating a Window with Named Arguments Source: https://www.lua.org/pil/5.3.html This example demonstrates creating a GUI window using a table for named arguments, including position, size, title, and background color. ```lua w = Window{ x=0, y=0, width=300, height=200, title = "Lua", background="blue", border = true } ``` -------------------------------- ### Lua Multiple Assignment Example Source: https://www.lua.org/manual/5.5/manual.html Illustrates how Lua handles multiple assignments, ensuring reads get values before assignments, even when variables are reassigned within the same statement. ```lua i = 3 i, a[i] = i+1, 20 ``` ```lua x, y = y, x ``` ```lua x, y, z = y, z, x ``` -------------------------------- ### Create and Populate a Lua Table Source: https://www.lua.org/pil/2.5.html Demonstrates creating an empty table and adding entries with both string and numeric keys. Shows how to access and modify values. ```lua a = {} k = "x" a[k] = 10 -- new entry, with key="x" and value=10 a[20] = "great" -- new entry, with key=20 and value="great" print(a["x"]) k = 20 print(a[k]) a["x"] = a["x"] + 1 -- increments entry "x" print(a["x"]) ``` -------------------------------- ### Main Program with Thread Creation Source: https://www.lua.org/pil/9.4.html This code demonstrates how to create multiple threads for downloading documents from a host and then calls the dispatcher to manage their execution. It sets up four download tasks. ```lua host = "www.w3.org" get(host, "/TR/html401/html40.txt") get(host,"/TR/2002/REC-xhtml1-20020801/xhtml1.pdf") get(host,"/TR/REC-html32.html") get(host, "/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt") dispatcher() -- main loop ``` -------------------------------- ### Lua Single-Method Object Usage Example Source: https://www.lua.org/pil/16.5.html Demonstrates how to use a single-method object created by the newObject factory. It shows getting and setting the object's internal value. ```lua d = newObject(0) print(d("get")) --> 0 d("set", 10) print(d("get")) --> 10 ``` -------------------------------- ### Lua Unpack Maximum Indices Crash Example Source: https://www.lua.org/bugs.html Shows a case where `unpack` can crash due to arithmetic overflow when called with maximum possible indices, specifically when both start and end indices are `2^31-1`. ```lua print(unpack({1,2,3}, 2^31-1, 2^31-1)) ``` -------------------------------- ### Example Tables for Shared Parts Source: https://www.lua.org/pil/12.1.2.html Defines two Lua tables, 'a' and 'b', where 'b' references a sub-table of 'a' (b.k = a[1]). This setup is used to demonstrate saving multiple tables with shared components. ```lua a = {{"one", "two"}, 3} b = {k = a[1]} ``` -------------------------------- ### Lua Constructor for Table Initialization Source: https://www.lua.org/spe.html This example illustrates using a constructor function (e.g., 'Window') to create and initialize a table with specific properties. This syntax provides a higher-level abstraction for object creation. ```lua window1 = Window{ x = 200, y = 300, foreground = "blue" } ``` -------------------------------- ### Get Function Information with lua_getinfo Source: https://www.lua.org/manual/5.5/manual.html Use lua_getinfo to retrieve details about a function or function invocation. The 'what' parameter specifies which fields of the lua_Debug structure to fill. For function introspection, push the function onto the stack and start 'what' with '>'. ```c int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); ``` ```c lua_Debug ar; lua_getglobal(L, "f"); /* get global 'f' */ lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined); ``` -------------------------------- ### Chaining Producer, Filter, and Consumer Source: https://www.lua.org/pil/9.2.html Shows the setup for the producer-filter-consumer chain by creating the producer, then the filter using the producer, and finally running the consumer with the filter. ```lua p = producer() f = filter(p) consumer(f) ``` -------------------------------- ### Get Closure Value Source: https://www.lua.org/source/5.5/lobject.h.html Macros to extract the underlying function pointer or closure structure from a `TValue` object. `clvalue` gets a generic closure, `clLvalue` gets a Lua closure, `fvalue` gets a light C function, and `clCvalue` gets a C closure. ```c #define clvalue(o) check_exp(ttisclosure(o), gco2cl(val_(o).gc)) #define clLvalue(o) check_exp(ttisLclosure(o), gco2lcl(val_(o).gc)) #define fvalue(o) check_exp(ttislcf(o), val_(o).f) #define clCvalue(o) check_exp(ttisCclosure(o), gco2ccl(val_(o).gc)) ``` -------------------------------- ### Lua Table Constructor Expansion Source: https://www.lua.org/manual/5.5/manual.html Shows the equivalent explicit code for the table constructor example, demonstrating how fields are assigned. ```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 Installation Directory Name Source: https://www.lua.org/work/diffs-lua-5.4.3-lua-5.4.4.txt Specifies the name of the top-level directory for Lua installation, which is 'lua-5.4.4'. ```html the top-level directory, which is named lua-5.4.4. ``` -------------------------------- ### Example: string.find with unpack Source: https://www.lua.org/pil/5.1.html Demonstrates calling `string.find` with arguments provided by `unpack`. This illustrates a practical application of generic calls. ```lua f = string.find a = {"hello", "ll"} f(unpack(a)) ``` -------------------------------- ### Illustrate Metamethod Retrieval with rawget Source: https://www.lua.org/work/diffs-lua-5.3.2-lua-5.3.3.txt This snippet shows an addition to the manual that illustrates how Lua retrieves metamethods using `rawget`, providing an example of the equivalent code. ```diff diff -r lua-5.3.2/doc/manual.html lua-5.3.3/doc/manual.html 393a412,414 > Lua queries metamethods in metatables using a raw access (see rawget). > So, to retrieve the metamethod for event ev in object o, > Lua does the equivalent to the following code: 394a416,418 >
> 	rawget(getmetatable(o) or {}, "__ev")
> 	
``` -------------------------------- ### Lua 5.4.3 Signal Handler Installation Source: https://www.lua.org/work/diffs-lua-5.4.2-lua-5.4.3.txt Installs a C-signal handler for SIGINT using the `setsignal` function. ```C setsignal(SIGINT, laction); /* set C-signal handler */ ``` -------------------------------- ### Correct Lua Guides Requirement Wording Source: https://www.lua.org/pil/errata.html Corrects a grammatical error in the description of Lua guides' requirements. ```text guides require is a little different ``` -------------------------------- ### traceback function example Source: https://www.lua.org/pil/23.1.html An example function demonstrating the use of `debug.getinfo` to print a primitive traceback of the active stack. ```APIDOC ## traceback function example ### Description This function iterates through the active stack levels, using `debug.getinfo` to retrieve and print information about each function, including its source and current line number. ### Code ```lua function traceback () local level = 1 while true do local info = debug.getinfo(level, "Sl") if not info then break end if info.what == "C" then -- is a C function? print(level, "C function") else -- a Lua function print(string.format("[%s]:%d", info.short_src, info.currentline)) end level = level + 1 end end ``` ### Usage Call the `traceback()` function to print the stack trace. ``` -------------------------------- ### Lua Table Constructor Example Source: https://www.lua.org/manual/5.5/manual.html Illustrates the creation of a table with various field initializations, including computed keys and sequential integer keys. ```lua a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } ``` -------------------------------- ### utf8.offset (s, n, i) Source: https://www.lua.org/work/diffu-lua-5.3.2-lua-5.3.3.txt Returns the starting byte index of the `n`-th character in a UTF-8 string, starting the search from index `i`. ```APIDOC ## utf8.offset (s, n, i) ### Description Returns the starting byte index of the `n`-th character in the UTF-8 string `s`, starting the search from index `i`. If `n` is negative, it searches backwards from the end of the string. Invalid UTF-8 sequences are handled correctly. Returns `nil` if the index is out of range. ### Parameters - **s** (string) - The UTF-8 encoded string. - **n** (integer) - The character number to find the offset of. - **i** (integer, optional) - The starting byte index for the search. Defaults to 1. ``` -------------------------------- ### Task Initialization and Event Assignment Source: https://www.lua.org/notes/ltn003.html Demonstrates the creation of a task object and the assignment of event handlers to specific events. It shows how to set up actions for events like Mouse_Click. ```lua mytask = w_task("MyTask",310, { [0] = M_DataLoad, [1] = M_Quit }) ..................... mytask.action[Mouse_Click] = function (self) ........ end ..................... mytask:poll() ``` -------------------------------- ### Initialize Expression Descriptor Source: https://www.lua.org/source/5.5/lparser.c.html Sets up an expression descriptor with its kind and associated information. ```c static void init_exp (expdesc *e, expkind k, int i) { e->f = e->t = NO_JUMP; e->k = k; e->u.info = i; } ``` -------------------------------- ### Lua API: Finish Raw Get Source: https://www.lua.org/work/diffu-lua-5.4.4-lua-5.4.5.txt Helper function to finalize a raw table get operation by placing the value on the stack. ```c if (isempty(val)) setnilvalue(s2v(L->top.p)); else setobj2s(L, L->top.p, val); api_incr_top(L); lua_unlock(L); return ttype(s2v(L->top.p - 1)); ``` -------------------------------- ### Lua List Constructor Example Source: https://www.lua.org/history.html Illustrates the original code for a list constructor in Lua. ```lua @[30, 40, 50] ``` -------------------------------- ### byteoffset Source: https://www.lua.org/source/5.5/lutf8lib.c.html Calculates the starting and ending byte indices of the n-th UTF-8 character in a string, optionally starting the count from a given position. ```APIDOC ## offset(s, n, [i]) ### Description Calculates the starting and ending byte indices of the n-th UTF-8 character in a string, optionally starting the count from a given position. If `n` is 0, it finds the starting byte of the character at position `i`. If `n` is positive, it finds the n-th character after position `i`. If `n` is negative, it finds the n-th character before position `i`. ### Parameters * `s` (string) - The UTF-8 encoded string. * `n` (integer) - The character number to find. 0 means the character at position `i`. Positive `n` counts forward, negative `n` counts backward. * `i` (integer, optional) - The starting position (1-based index) for counting characters. Defaults to 1 if `n` is positive, or the end of the string if `n` is negative. ### Returns * `integer` - The 1-based starting byte index of the character. * `integer` - The 1-based ending byte index of the character. * `nil` - If the n-th character cannot be found. ``` -------------------------------- ### Calling Functions as Statements and Expressions Source: https://www.lua.org/pil/5.html Demonstrates how to use function calls as statements for actions and as expressions for computing values. Includes examples with built-in and library functions. ```lua print(8*9, 9/8) a = math.sin(3) + math.cos(10) print(os.date()) ``` -------------------------------- ### Implement Autoloading for Lua Packages Source: https://www.lua.org/pil/15.5.html Set up a package with a `__index` metamethod that dynamically loads functions from auxiliary files when they are first accessed. This defers loading until necessary. ```lua pack1 = {} setmetatable(pack1, {__index = function (t, funcname) local file = location[funcname] if not file then error("package pack1 does not define " .. funcname) end assert(loadfile(file))() -- load and run definition return t[funcname] -- return the function end}) return pack1 ``` -------------------------------- ### Lua API: Raw Get Table Source: https://www.lua.org/work/diffu-lua-5.4.4-lua-5.4.5.txt Performs a raw get operation on a table, retrieving a value associated with a key without invoking metamethods. ```c TValue *t; const TValue *val; lua_lock(L); api_checknelems(L, 1); t = gettable(L, idx); val = luaH_get(t, s2v(L->top.p - 1)); L->top.p--; /* remove key */ return finishrawget(L, val); ``` -------------------------------- ### Lua Expression Evaluation Examples Source: https://www.lua.org/pil/3.5.html These examples demonstrate how Lua evaluates expressions based on operator precedence. They show the equivalent fully parenthesized expressions. ```text a+i < b/2+1 <--> (a+i) < ((b/2)+1) 5+x^2*8 <--> 5+((x^2)*8) a < y and y <= z <--> (a < y) and (y <= z) -x^2 <--> -(x^2) x^y^z <--> x^(y^z) ``` -------------------------------- ### Run a Lua script Source: https://www.lua.org/pil/1.html Demonstrates how to execute a Lua script file from the command line using the `lua` interpreter. ```bash prompt> lua hello.lua ``` -------------------------------- ### Define dofile using loadfile Source: https://www.lua.org/pil/8.html This demonstrates how to define the `dofile` function using `loadfile` and `assert` to handle potential loading errors. ```lua function dofile (filename) local f = assert(loadfile(filename)) return f() end ``` -------------------------------- ### Get Vararg Value Source: https://www.lua.org/source/5.5/ltm.c.html Retrieves a variable argument based on a key. The key can be an integer index or the string 'n' to get the total number of extra arguments. ```c void luaT_getvararg (CallInfo *ci, StkId ra, TValue *rc) { int nextra = ci->u.l.nextraargs; lua_Integer n; if (tointegerns(rc, &n)) { /* integral value? */ if (l_castS2U(n) - 1 < cast_uint(nextra)) { StkId slot = ci->func.p - nextra + cast_int(n) - 1; setobjs2s(((lua_State*)NULL), ra, slot); return; } } else if (ttisstring(rc)) { /* string value? */ size_t len; const char *s = getlstr(tsvalue(rc), len); if (len == 1 && s[0] == 'n') { /* key is "n"? */ setivalue(s2v(ra), nextra); return; } } setnilvalue(s2v(ra)); /* else produce nil */ } ``` -------------------------------- ### Creating a Lua List Table Source: https://www.lua.org/semish94.html Demonstrates creating a Lua table intended to be used as a list by providing its elements directly. ```lua t = @["red", "green", "blue", 3] ``` -------------------------------- ### Lua Integer Constant Examples Source: https://www.lua.org/manual/5.5/manual.html Examples of valid integer constants in Lua, including decimal and hexadecimal formats. Hexadecimal constants wrap around on overflow. ```lua 3 345 0xff 0xBEBADA ``` -------------------------------- ### Load File and Execute Code Interactively Source: https://www.lua.org/pil/1.4.html Combine -l to load a file and -e to execute code, then enter interactive mode with -i. This allows for sequential setup and execution. ```bash prompt> lua -i -l a.lua -e "x = 10" ``` -------------------------------- ### Optimized Integer Key Table Get Source: https://www.lua.org/work/diffs-lua-5.3.1-lua-5.3.2.txt Introduces a fast path for integer key table gets, checking for a quick lookup before performing a general finishget operation. ```c if (luaV_fastget(L, t, n, aux, luaH_getint)) { setobj2s(L, L->top, aux); api_incr_top(L); } else { setivalue(L->top, n); api_incr_top(L); luaV_finishget(L, t, L->top - 1, L->top - 1, aux); } ``` -------------------------------- ### Lua C API: Finish Raw Get Operation Source: https://www.lua.org/work/diffs-lua-5.4.3-lua-5.4.4.txt Completes a raw table get operation. It takes the value obtained from the table and returns an integer status. ```c static int finishrawget (lua_State *L, const TValue *val) { ``` ```c l_sinline int finishrawget (lua_State *L, const TValue *val) { ``` -------------------------------- ### Coroutine Execution Start Source: https://www.lua.org/work/diffu-lua-5.3.0-lua-5.3.1.txt Demonstrates how a coroutine begins execution when resumed for the first time. It clarifies how initial arguments are passed to the coroutine's main function. ```lua When you first call coroutine.resume, passing as its first argument a thread returned by coroutine.create, the coroutine starts its execution by calling its main function. Extra arguments passed to coroutine.resume are passed as arguments to that function. ``` -------------------------------- ### Download and Build Lua from Source Source: https://www.lua.org/download.html This snippet shows the commands to download the Lua source code, extract it, and build it using 'make'. It's suitable for users with a C compiler who want to compile Lua from scratch. ```bash curl -L -R -O https://www.lua.org/ftp/lua-5.5.0.tar.gz tar zxf lua-5.5.0.tar.gz cd lua-5.5.0 make all test ``` -------------------------------- ### Finish Raw Get Operation Source: https://www.lua.org/source/5.5/lapi.c.html Completes a raw table get operation by pushing the value onto the stack or nil if the tag is empty. This is an internal helper function. ```c static int finishrawget (lua_State *L, lu_byte tag) { if (tagisempty(tag)) /* avoid copying empty items to the stack */ setnilvalue(s2v(L->top.p)); api_incr_top(L); lua_unlock(L); return novariant(tag); } ``` -------------------------------- ### Lua Window Object Creation and Access Source: https://www.lua.org/pil/13.4.1.html Demonstrates creating a new window object using the constructor and accessing a property ('width'). This example shows how the __index metamethod automatically provides the default value from the prototype when the field is not explicitly set on the object. ```lua w = Window.new{x=10, y=20} print(w.width) --> 100 ``` -------------------------------- ### Stack Indexing Source: https://www.lua.org/pil/24.2.2.html Elements in the Lua stack can be accessed using positive indices (starting from 1 for the bottom element) or negative indices (starting from -1 for the top element). ```APIDOC ## Stack Indexing Elements in the stack are referred to using indices. The first element pushed has index 1, the next has index 2, and so on. Negative indices can also be used, where -1 refers to the top element, -2 to the previous, and so forth. ``` -------------------------------- ### Finalize Raw Table Get Operation in Lua Source: https://www.lua.org/work/diffu-lua-5.4.3-lua-5.4.4.txt Completes a raw table get operation by setting the value on the Lua stack. Handles empty slots by pushing nil. ```c l_sinline int finishrawget (lua_State *L, const TValue *val) { if (isempty(val)) /* avoid copying empty items to the stack */ setnilvalue(s2v(L->top)); else setobj(L, s2v(L->top), val); api_incr_top(L); return !isempty(val); } ``` -------------------------------- ### Hello World in Lua Source: https://www.lua.org/extras A basic 'Hello World' program in Lua, demonstrating output to the console and using the Lua version. ```lua -- the first program in every language io.write("Hello world, from ",_VERSION,"!\n") ``` -------------------------------- ### Simplify Match State Preparation in Lua Source: https://www.lua.org/work/diffs-lua-5.3.1-lua-5.3.2.txt Streamlines the initialization of the match state by directly calling 'prepstate'. ```c ms.L = L; ms.matchdepth = MAXCCALLS; ms.src_init = src; ms.src_end = src+srcl; ms.p_end = p + lp; ``` ```c prepstate(&ms, L, src, srcl, p, lp); ``` -------------------------------- ### Lua require Fixed Path Example Source: https://www.lua.org/pil/8.1.html Presents an example of a `require` path that includes a fixed file name component. This component is used directly without pattern matching. ```lua ?;?.lua;/usr/local/default.lua ``` -------------------------------- ### Create Resizable Memory in Lua Source: https://www.lua.org/wshop18/Maia Shows how to create a resizable memory block, resize it, fill it with a specific byte, and observe content changes after resizing. ```lua resizable = memory.create() assert(memory.type(resizable) == "resizable") assert(memory.len(resizable) == 0) memory.resize(resizable, 4) assert(memory.len(resizable) == 4) assert(memory.tostring(resizable) == "\0\0\0\0") memory.fill(resizable, 0xff) assert(memory.tostring(resizable) == "\xff\xff\xff\xff") memory.resize(resizable, 8) assert(memory.tostring(resizable) == "\xff\xff\xff\xff\0\0\0\0") memory.resize(resizable, 6) assert(memory.tostring(resizable) == "\xff\xff\xff\xff\0\0") ``` -------------------------------- ### Initialize Lexical State Source: https://www.lua.org/source/5.5/llex.c.html Sets up the LexState structure for a new input source. Ensures essential strings like '_ENV' and 'break' are properly handled and initializes the buffer. ```c void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, int firstchar) { ls->t.token = 0; ls->L = L; ls->current = firstchar; ls->lookahead.token = TK_EOS; /* no look-ahead token */ ls->z = z; ls->fs = NULL; ls->linenumber = 1; ls->lastline = 1; ls->source = source; /* all three strings here ("_ENV", "break", "global") were fixed, so they cannot be collected */ ls->envn = luaS_newliteral(L, LUA_ENV); /* get env string */ ls->brkn = luaS_newliteral(L, "break"); /* get "break" string */ #if defined(LUA_COMPAT_GLOBAL) /* compatibility mode: "global" is not a reserved word */ ls->glbn = luaS_newliteral(L, "global"); /* get "global" string */ ls->glbn->extra = 0; /* mark it as not reserved */ #endif luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ } ``` -------------------------------- ### Conditional Lua Configuration Example Source: https://www.lua.org/pil/25.html A Lua configuration file that sets window dimensions based on the DISPLAY environment variable. ```lua -- configuration file for program `pp' if getenv("DISPLAY") == ":0.0" then width = 300; height = 300 else width = 200; height = 200 end ``` -------------------------------- ### Check for 'local' keyword at line start Source: https://www.lua.org/source/5.5/lua.c.html Checks if a line starts with the 'local' keyword followed by a space, issuing a warning if it does, as locals do not persist across lines in interactive mode. ```c static void checklocal (const char *line) { static const size_t szloc = sizeof("local") - 1; static const char space[] = " "; line += strspn(line, space); /* skip spaces */ if (strncmp(line, "local", szloc) == 0 && /* "local"? */ strchr(space, *(line + szloc)) != NULL) { /* followed by a space? */ lua_writestringerror("%s\n", "warning: locals do not survive across lines in interactive mode"); } } ``` -------------------------------- ### Lua Record Initialization Source: https://www.lua.org/history.html Demonstrates how to initialize a record-like structure in Lua using associative tables. Fields are accessed using string keys. ```lua t1 = @track { y = 9, x = 10, z="hi!" } ```