### Lua string.gsub pattern substitution examples Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows multiple uses of string.gsub: duplicating captured words, limiting replacements with a count, swapping word order, using os.getenv for environment variable substitution, evaluating expressions with a function, and using a table for replacements. Each example includes the resulting output. ```lua x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return load(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.2"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.2.tar.gz" ``` -------------------------------- ### Create and print an array with nested tables Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how to create an array with mixed values, including a nested table, and how to get its length using the # operator. ```lua local array = {5, "text", {"more text", 463, "even more text"}, "more text"} print(#array) --> 4 ; the # operator for strings can also be used for arrays, in which case it will return the number of values in the array -- This example demonstrates how tables can be nested in other tables. Since tables themselves are values, tables can include other tables. Arrays of tables are called multi-dimensional arrays. ``` -------------------------------- ### coroutine.resume Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Starts or continues the execution of a coroutine. Passes arguments to the coroutine and returns values yielded or returned by it, along with a success flag. ```APIDOC ## coroutine.resume ### Description Starts or continues the execution of a coroutine. Passes arguments to the coroutine and returns values yielded or returned by it, along with a success flag. ### Method Function ### Signature `coroutine.resume(co, val1, ...)` ### Parameters - **co** (thread) - Required - The coroutine to resume. - **val1, ...** (any) - Optional - Arguments passed to the coroutine (as arguments to the function or as return values from yield). ### Returns - **success** (boolean) - `true` if execution was successful, `false` otherwise. - **values** (any) - If successful, the values returned by the coroutine (if terminated) or passed to `coroutine.yield` (if suspended). If unsuccessful, an error message. ### Example ```lua local co = coroutine.create(function(a) return a end) local ok, result = coroutine.resume(co, 3) ``` ``` -------------------------------- ### Defining and calling a method with dot syntax Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Defines a function in a table using a dot and passes the table explicitly as the first argument. This is equivalent to the colon syntax example. ```lua local object = {} function object.func(self, arg1, arg2) print(arg1, arg2) end object.func(object, 1, 2) --> 1, 2 ``` -------------------------------- ### Coroutine example with create, resume, and yield Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows a coroutine that yields a value, is resumed with a new value, and returns a result. The main thread resumes with 3, receives 5, then resumes with 10, and prints 7. Note that coroutine.resume returns true plus values on success. ```lua local co = coroutine.create(function(initial_value) local value_obtained = coroutine.yield(initial_value + 2) -- 3+2=5 return value_obtained - initial_value -- 10-3=7 end) local _, initial_result = coroutine.resume(co, 3) -- initial_result: 5 local _, final_result = coroutine.resume(co, initial_result * 2) -- 5*2=10 print(final_result) --> 7 ``` -------------------------------- ### Find literal substring using method syntax Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Equivalent to the previous example but uses the colon method syntax on the string variable. This works because the index metamethod of strings points to the string library functions. ```lua local sentence = "The quick brown fox jumps over the lazy dog." local start_position, end_position = sentence:find("lazy", 1, true) print("The word \"lazy\" was found starting at position " .. start_position .. " and ending at position " .. end_position .. ".") ``` -------------------------------- ### Lua: Recommended semicolon before parenthesis statement Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows the recommended practice of preceding a statement that starts with a parenthesis with a semicolon to avoid ambiguity. ```lua ;(print or io.write)('done') ``` -------------------------------- ### string.find Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Searches for the first match of a pattern in a string. Returns the start and end indices of the match, or nothing if no match is found. Supports optional start index and plain match mode. ```APIDOC ## string.find ### Description Searches for the first occurrence of a pattern in a string. Returns the start and end indices of the match, or nothing if no match is found. Can perform a plain (non-pattern) search when the fourth argument is true. ### Method Function call ### Endpoint string.find(s, pattern [, init [, plain]]) ### Parameters #### Arguments - **s** (string) - Required - The string to search in. - **pattern** (string) - Required - The pattern to search for. Can be a plain string if plain is true. - **init** (integer) - Optional - The character position to start searching from. Defaults to 1. Negative numbers index from the end of the string. - **plain** (boolean) - Optional - If true, performs a simple match without pattern matching. Must be provided with init. ### Return Values - **start** (integer) - The index of the first character of the match. - **end** (integer) - The index of the last character of the match. - If no match is found, returns nothing. ### Example ```lua local start_position, end_position = string.find("The quick brown fox jumps over the lazy dog.", "lazy", 1, true) print("The word \"lazy\" was found starting at position " .. start_position .. " and ending at position " .. end_position .. ".") ``` ### Notes - Indices start at 1 for the first character. - Negative indices are interpreted as counting from the end of the string, with the last character at position -1. - The string library functions can be called using colon notation: `s:find(pattern, init, plain)`. ``` -------------------------------- ### Parallel assignment with table field Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version This example shows that parallel assignment evaluates all variables and values before assigning, so `dictionary[2]` is set to 12, not `dictionary[1]`. ```lua dictionary = {} index = 2 index, dictionary[index] = index - 1, 12 ``` -------------------------------- ### Syntactic error example: print(5 ++ 4 return) Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Invalid Lua code that causes a syntactic error because it does not follow Lua's grammar rules. ```lua print(5 ++ 4 return) ``` -------------------------------- ### Using the type function to get a number's type Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Demonstrates the type function returning the string 'number' for a numeric literal. The output is shown as a comment. ```lua print(type(32425)) --> number ``` -------------------------------- ### Lua variadic function example: add_one Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Demonstrates a variadic function that adds the first argument to all other arguments and sums them. The function uses the vararg expression {...} to iterate over extra arguments. ```lua function add_one(increment, ...) local result = 0 for _, number in next, {...} do result = result + number + increment end end ``` -------------------------------- ### Lua automatic string-number coercion examples Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows automatic coercion: arithmetic on a string converts it to a number, and concatenation converts a number to a string. Outputs are shown as comments. ```lua print("122" + 1) --> 123 print("The number is " .. 5 .. ".") --> The number is 5. ``` -------------------------------- ### Lua select function to distinguish nil from no value Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how the select function with '#' as first argument can distinguish between passing nil and passing no value. The example prints 'no value' when no argument is passed and 'nil' when nil is passed. ```lua print((function(...) return select('#', ...) == 1 and "nil" or "no value" end)()) --> no value print((function(...) return select('#', ...) == 1 and "nil" or "no value" end)(nil)) --> nil print((function(...) return select('#', ...) == 1 and "nil" or "no value" end)(variable_that_is_not_defined)) --> nil -- As this code shows, the function is able to detect whether the value nil was passed as an argument or whether there was simply no value passed. -- In normal circumstances, both are considered as nil, and this is the only way to distinguish them. ``` -------------------------------- ### Parallel assignment in Lua Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Lua supports parallel assignment, allowing multiple variables to be assigned values in a single statement. This example assigns 0 to a, b, c, and d. ```lua a, b, c, d = 0, 0, 0, 0 ``` -------------------------------- ### Lua: Ambiguous statement starting with parenthesis Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows a fragment where a statement starting with a parenthesis can be misinterpreted. The parser interprets the opening parenthesis as the start of arguments to the previous call, so it is good practice to precede such statements with a semicolon. ```lua a = b + c (print or io.write)('done') ``` -------------------------------- ### Create a multi-line table with semicolons Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Demonstrates a multi-line table constructor using semicolons and including a nested table and a boolean value. ```lua local array = { "text"; { "more text, in a nested table"; 1432 }; true -- booleans can also be in tables } ``` -------------------------------- ### Create a dictionary with mixed key types Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how to create a dictionary with various key types: implicit numeric, string keys via identifier, explicit numeric key, function value, and string key with brackets. ```lua local dictionary = { "text"; text = "more text"; 654; [8] = {}; -- an empty table func = function() print("tables can even contain functions!") end; ["1213"] = 1213 } ``` -------------------------------- ### Hello world program in Lua Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Basic Lua program that prints 'Hello, world!' using the print function. Note that in embedded applications, print may not always display to the user. ```lua print("Hello, world!") ``` -------------------------------- ### string.sub Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Returns the substring of a string that starts at and ends at the two character positions given as arguments. ```APIDOC ## string.sub ### Description Returns the substring of a string that starts at and ends at the two character positions given as arguments. ### Method Function ### Signature string.sub(s, i [, j]) ### Parameters - **s** (string) - Required - The string from which to extract the substring. - **i** (number) - Required - The starting position (1-based). - **j** (number) - Optional - The ending position (1-based). Defaults to the end of the string. ### Return Value Returns the substring from position i to position j. ``` -------------------------------- ### Lua string length with # operator Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Uses the unary length operator '#' to get the length of a string, printing 16. ```lua print(#("This is a string")) --> 16 ``` -------------------------------- ### Long comments in Lua Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Demonstrates long comments that span multiple lines, starting with a long bracket (--[[ ... ]]). ```lua print("This is normal code") --[[Line 1 Line 2 ]] ``` -------------------------------- ### Iterate over lines in a file with io.open:lines Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Prints all lines from 'file.txt' using the file:lines iterator returned by io.open. The loop variable 'line' receives each line until the iterator returns nil. ```lua for line in io.open("file.txt"):lines() do print(line) end ``` -------------------------------- ### Define a Lua function with a function constructor Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Creates a function with three parameters and stores it in a local variable. The function body is a placeholder comment. ```lua local func = function(first_parameter, second_parameter, third_parameter) -- function body (a function's body is the code it contains) end ``` -------------------------------- ### string.lower Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Returns the lowercase equivalent of a string. ```APIDOC ## string.lower ### Description Returns the lowercase equivalent of a string. ### Method Function ### Signature string.lower(s) ### Parameters - **s** (string) - Required - The string to convert to lowercase. ### Return Value Returns the lowercase version of the string. ``` -------------------------------- ### string.upper Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Returns the uppercase equivalent of a string. ```APIDOC ## string.upper ### Description Returns the uppercase equivalent of a string. ### Method Function ### Signature string.upper(s) ### Parameters - **s** (string) - Required - The string to convert to uppercase. ### Return Value Returns the uppercase version of the string. ``` -------------------------------- ### Basic variable assignment and access Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Assigns the value 43 to the variable 'variable' and prints it, showing how to access a variable's value. ```lua variable = 43 print(variable) --> 43 ``` -------------------------------- ### string.len Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Returns the length of a string. ```APIDOC ## string.len ### Description Returns the length of a string. ### Method Function ### Signature string.len(s) ### Parameters - **s** (string) - Required - The string whose length is to be returned. ### Return Value Returns the number of characters in the string. ``` -------------------------------- ### Foreach loop with next function Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Iterates over an array using the next function, printing each index and value plus one. The output is shown in comments. ```lua local array = {5, 2, 6, 3, 6} for index, value in next, array do print(index .. ": " .. value + 1) end -- Output: -- 1: 6 -- 2: 3 -- 3: 7 -- 4: 4 -- 5: 7 ``` -------------------------------- ### Define a Lua function using syntactic sugar Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Equivalent to the previous constructor but uses the local function syntax. This form allows the function to refer to itself because it translates to local foo; foo = function() end. ```lua local function func(first_parameter, second_parameter, third_parameter) -- function body end ``` -------------------------------- ### Lua while loop printing numbers 0-9 Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Uses a while loop to print numbers from 0 to 9. The condition is checked at the start of each iteration, so if the initial value is already >= 10, the loop body never executes. ```lua local number = 0 while number < 10 do print(number) number = number + 1 -- Increase the value of the number by one. end ``` -------------------------------- ### Access a table value using bracket notation Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how to access a value in a table using the index inside brackets. ```lua local dictionary = {number = 6} print(dictionary["number"]) --> 6 ``` -------------------------------- ### Use generic for loop with seq, nil, 0 tuple Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Uses the generic for loop with the transformation function 'seq', a nil state, and initial value 0 to print numbers from 1 to 10. ```lua -- This will display the numbers from 1 to 10. for value in seq, nil, 0 do print(value) end ``` -------------------------------- ### Static semantic error example: print("hello" + 5) Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Valid Lua syntax but causes a static semantic error because adding a string and a number is not allowed (unless the string represents a number and is coerced). ```lua print("hello" + 5) ``` -------------------------------- ### Lua string literal examples with quotes and long brackets Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows valid and invalid string literals, including escape sequences and long bracket strings that can span multiple lines and contain any characters except closing long brackets of the same level. ```lua "This is a valid string." 'This is also a valid string.' "This is a valid \" string 'that contains unescaped single quotes and escaped double quotes." [[ This is a line that can continue on more than one line. It can contain single quotes, double quotes and everything else (-- including comments). It ignores everything (including escape characters) except closing long brackets of the same level as the opening long bracket. ]] "This is a valid string that contains tabs \t, double quotes \" and backlashes \\" "This is " not a valid string because there is an unescaped double quote in the middle of it." ``` -------------------------------- ### Find literal substring with string.find Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Searches for the literal word "lazy" in a sentence using string.find with the plain flag set to true. Prints the start and end positions of the match. The third argument (1) is required when performing a simple match. ```lua local start_position, end_position = string.find("The quick brown fox jumps over the lazy dog.", "lazy", 1, true) print("The word \"lazy\" was found starting at position " .. start_position .. " and ending at position " .. end_position .. ".") ``` -------------------------------- ### Short comments in Lua Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how to write short comments in Lua, either on their own line or at the end of a line of code. Comments are prefixed by two hyphens. ```lua print("This is normal code.") -- This is a comment print("This is still normal code.") -- This is a comment at the end of a line of code. ``` -------------------------------- ### Returning a tuple and converting to array Source: https://en.wikibooks.org/wiki/Lua_Programming/Single_page_version Shows how a function returning multiple values evaluates to a tuple, which can be stored in an array or assigned to multiple variables. The print call also receives the tuple. ```lua function return_tuple() return 5, 6 -- Because this function returns two values, a function call to it evaluates to a tuple. end local array = {return_tuple()} -- same as local array = {5, 6} local a, b = return_tuple() -- same as local a, b = 5, 6 print(return_tuple()) -- same as print(5, 6) ```