\endp\subsubsection{Coercion} \begp Lua provides automatic conversion between string and number values at run time. Any arithmetic operation applied to a string tries to convert this string to a number, following the usual conversion rules. Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control over how numbers are converted to strings, use the \begcode format\endcode function from the string library (see %\begcode string.format\endcode ). \endp\subsection{Variables} \begp Variables are places that store values. There are three kinds of variables in Lua: global variables, local variables, and table fields. \endp\begp A single name can denote a global variable or a local variable (or a function's formal parameter, which is a particular kind of local variable): \endp\begpre var ::= Name \endpre \begp Name denotes identifiers, as defined in %§2.1. \endp\begp Any variable is assumed to be global unless explicitly declared as a local (see %§2.4.7). Local variables are {\em lexically scoped}: local variables can be freely accessed by functions defined inside their scope (see %§2.6). \endp\begp Before the first assignment to a variable, its value is {\bf nil}. \endp\begp Square brackets are used to index a table: \endp\begpre var ::= prefixexp `{\bf [} exp `{\bf ]} \endpre \begp The meaning of accesses to global variables and table fields can be changed via metatables. An access to an indexed variable \begcode t[i]\endcode is equivalent to a call \begcode gettable_event(t,i)\endcode . (See %§2.8 for a complete description of the \begcode gettable_event\endcode function. This function is not defined or callable in Lua. We use it here only for explanatory purposes.) \endp\begp The syntax \begcode var.Name\endcode is just syntactic sugar for \begcode var["Name"]\endcode : \endp\begpre var ::= prefixexp `{\bf .} Name \endpre \begp All global variables live as fields in ordinary Lua tables, called {\em environment tables} or simply {\em environments} (see %§2.9). Each function has its own reference to an environment, so that all global variables in this function will refer to this environment table. When a function is created, it inherits the environment from the function that created it. To get the environment table of a Lua function, you call %\begcode getfenv\endcode . To replace it, you call %\begcode setfenv\endcode . (You can only manipulate the environment of C~functions through the debug library; (see %§5.9).) \endp\begp An access to a global variable \begcode x\endcode is equivalent to \begcode _env.x\endcode , which in turn is equivalent to \endp\begpre gettable_event(_env, "x") \endpre \begp where \begcode _env\endcode is the environment of the running function. (See %§2.8 for a complete description of the \begcode gettable_event\endcode function. This function is not defined or callable in Lua. Similarly, the \begcode _env\endcode variable is not defined in Lua. We use them here only for explanatory purposes.) \endp\subsection{Statements} \begp Lua supports an almost conventional set of statements, similar to those in Pascal or C. This set includes assignments, control structures, function calls, and variable declarations. \endp\subsubsection{Chunks} \begp The unit of execution of Lua is called a {\em chunk}. A chunk is simply a sequence of statements, which are executed sequentially. Each statement can be optionally followed by a semicolon: \endp\begpre chunk ::= {stat [`{\bf ;} ]} \endpre \begp There are no empty statements and thus '\begcode ;;\endcode ' is not legal. \endp\begp Lua handles a chunk as the body of an anonymous function with a variable number of arguments (see %§2.5.9). As such, chunks can define local variables, receive arguments, and return values. \endp\begp A chunk can be stored in a file or in a string inside the host program. To execute a chunk, Lua first pre-compiles the chunk into instructions for a virtual machine, and then it executes the compiled code with an interpreter for the virtual machine. \endp\begp Chunks can also be pre-compiled into binary form; see program \begcode luac\endcode for details. Programs in source and compiled forms are interchangeable; Lua automatically detects the file type and acts accordingly. \endp\subsubsection{Blocks}\begp A block is a list of statements; syntactically, a block is the same as a chunk: \endp\begpre block ::= chunk \endpre \begp A block can be explicitly delimited to produce a single statement: \endp\begpre stat ::= {\bf do} block {\bf end} \endpre \begp Explicit blocks are useful to control the scope of variable declarations. Explicit blocks are also sometimes used to add a {\bf return} or {\bf break} statement in the middle of another block (see %§2.4.4). \endp\subsubsection{Assignment} \begp Lua allows multiple assignments. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas: \endp\begpre stat ::= varlist `{\bf =} explist varlist ::= var {`{\bf ,} var} explist ::= exp {`{\bf ,} exp} \endpre \begp Expressions are discussed in %§2.5. \endp\begp Before the assignment, the list of values is {\em adjusted} to the length of the list of variables. If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with as many {\bf nil}'s as needed. If the list of expressions ends with a function call, then all values returned by that call enter the list of values, before the adjustment (except when the call is enclosed in parentheses; see %§2.5). \endp\begp The assignment statement first evaluates all its expressions and only then are the assignments performed. Thus the code \endp\begpre i = 3 i, a[i] = i+1, 20 \endpre \begp sets \begcode a[3]\endcode to 20, without affecting \begcode a[4]\endcode because the \begcode i\endcode in \begcode a[i]\endcode is evaluated (to 3) before it is assigned~4. Similarly, the line \endp\begpre x, y = y, x \endpre \begp exchanges the values of \begcode x\endcode and \begcode y\endcode , and \endp\begpre x, y, z = y, z, x \endpre \begp cyclically permutes the values of \begcode x\endcode , \begcode y\endcode , and \begcode z\endcode . \endp\begp The meaning of assignments to global variables and table fields can be changed via metatables. An assignment to an indexed variable \begcode t[i] = val\endcode is equivalent to \begcode settable_event(t,i,val)\endcode . (See %§2.8 for a complete description of the \begcode settable_event\endcode function. This function is not defined or callable in Lua. We use it here only for explanatory purposes.) \endp\begp An assignment to a global variable \begcode x = val\endcode is equivalent to the assignment \begcode _env.x = val\endcode , which in turn is equivalent to \endp\begpre settable_event(_env, "x", val) \endpre \begp where \begcode _env\endcode is the environment of the running function. (The \begcode _env\endcode variable is not defined in Lua. We use it here only for explanatory purposes.) \endp\subsubsection{Control Structures}\begp The control structures {\bf if}, {\bf while}, and {\bf repeat} have the usual meaning and familiar syntax: \endp\begpre stat ::= {\bf while} exp {\bf do} block {\bf end} stat ::= {\bf repeat} block {\bf until} exp stat ::= {\bf if} exp {\bf then} block {{\bf elseif} exp {\bf then} block} [{\bf else} block] {\bf end} \endpre \begp Lua also has a {\bf for} statement, in two flavors (see %§2.4.5). \endp\begp The condition expression of a control structure can return any value. Both {\bf false} and {\bf nil} are considered false. All values different from {\bf nil} and {\bf false} are considered true (in particular, the number 0 and the empty string are also true). \endp\begp In the {\bf repeat}–{\bf until} loop, the inner block does not end at the {\bf until} keyword, but only after the condition. So, the condition can refer to local variables declared inside the loop block. \endp\begp The {\bf return} statement is used to return values from a function or a chunk (which is just a function). Functions and chunks can return more than one value, and so the syntax for the {\bf return} statement is \endp\begpre stat ::= {\bf return} [explist] \endpre \begp The {\bf break} statement is used to terminate the execution of a {\bf while}, {\bf repeat}, or {\bf for} loop, skipping to the next statement after the loop: \endp\begpre stat ::= {\bf break} \endpre \begp A {\bf break} ends the innermost enclosing loop. \endp\begp The {\bf return} and {\bf break} statements can only be written as the {\em last} statement of a block. If it is really necessary to {\bf return} or {\bf break} in the middle of a block, then an explicit inner block can be used, as in the idioms \begcode do return end\endcode and \begcode do break end\endcode , because now {\bf return} and {\bf break} are the last statements in their (inner) blocks. \endp\subsubsection{For Statement} \begp The {\bf for} statement has two forms: one numeric and one generic. \endp\begp The numeric {\bf for} loop repeats a block of code while a control variable runs through an arithmetic progression. It has the following syntax: \endp\begpre stat ::= {\bf for} Name `{\bf =} exp `{\bf ,} exp [`{\bf ,} exp] {\bf do} block {\bf end} \endpre \begp The {\em block} is repeated for {\em name} starting at the value of the first {\em exp}, until it passes the second {\em exp} by steps of the third {\em exp}. More precisely, a {\bf for} statement like \endp\begpre for v = {\em e1}, {\em e2}, {\em e3} do {\em block} end \endpre \begp is equivalent to the code: \endp\begpre do local {\em var}, {\em limit}, {\em step} = tonumber({\em e1}), tonumber({\em e2}), tonumber({\em e3}) if not ({\em var} and {\em limit} and {\em step}) then error() end while ({\em step} > 0 and {\em var} <= {\em limit}) or ({\em step} <= 0 and {\em var} >= {\em limit}) do local v = {\em var} {\em block} {\em var} = {\em var} + {\em step} end end \endpre \begp Note the following: \endp \begp The generic {\bf for} statement works over functions, called {\em iterators}. On each iteration, the iterator function is called to produce a new value, stopping when this new value is {\bf nil}. The generic {\bf for} loop has the following syntax: \endp\begpre stat ::= {\bf for} namelist {\bf in} explist {\bf do} block {\bf end} namelist ::= Name {`{\bf ,} Name} \endpre \begp A {\bf for} statement like \endp\begpre for {\em var_1}, %·%·%·, {\em var_n} in {\em explist} do {\em block} end \endpre \begp is equivalent to the code: \endp\begpre do local {\em f}, {\em s}, {\em var} = {\em explist} while true do local {\em var_1}, %·%·%·, {\em var_n} = {\em f}({\em s}, {\em var}) {\em var} = {\em var_1} if {\em var} == nil then break end {\em block} end end \endpre \begp Note the following: \endp \subsubsection{Function Calls as Statements}\begp To allow possible side-effects, function calls can be executed as statements: \endp\begpre stat ::= functioncall \endpre \begp In this case, all returned values are thrown away. Function calls are explained in %§2.5.8. \endp\subsubsection{Local Declarations}\begp Local variables can be declared anywhere inside a block. The declaration can include an initial assignment: \endp\begpre stat ::= {\bf local} namelist [`{\bf =} explist] \endpre \begp If present, an initial assignment has the same semantics of a multiple assignment (see %§2.4.3). Otherwise, all variables are initialized with {\bf nil}. \endp\begp A chunk is also a block (see %§2.4.1), and so local variables can be declared in a chunk outside any explicit block. The scope of such local variables extends until the end of the chunk. \endp\begp The visibility rules for local variables are explained in %§2.6. \endp\subsection{Expressions} \begp The basic expressions in Lua are the following: \endp\begpre exp ::= prefixexp exp ::= {\bf nil} | {\bf false} | {\bf true} exp ::= Number exp ::= String exp ::= function exp ::= tableconstructor exp ::= `{\bf ...} exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | `{\bf (} exp `{\bf )} \endpre \begp Numbers and literal strings are explained in %§2.1; variables are explained in %§2.3; function definitions are explained in %§2.5.9; function calls are explained in %§2.5.8; table constructors are explained in %§2.5.7. Vararg expressions, denoted by three dots ('\begcode ...\endcode '), can only be used when directly inside a vararg function; they are explained in %§2.5.9. \endp\begp Binary operators comprise arithmetic operators (see %§2.5.1), relational operators (see %§2.5.2), logical operators (see %§2.5.3), and the concatenation operator (see %§2.5.4). Unary operators comprise the unary minus (see %§2.5.1), the unary {\bf not} (see %§2.5.3), and the unary {\em length operator} (see %§2.5.5). \endp\begp Both function calls and vararg expressions can result in multiple values. If an expression is used as a statement (only possible for function calls (see %§2.4.6)), then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, discarding all values except the first one. \endp\begp Here are some examples: \endp\begpre f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all results from f() a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil) a,b = ... -- a gets the first vararg parameter, b gets -- the second (both a and b can get nil if there -- is no corresponding vararg parameter) a,b,c = x, f() -- f() is adjusted to 2 results a,b,c = f() -- f() is adjusted to 3 results return f() -- returns all results from f() return ... -- returns all received vararg parameters return x,y,f() -- returns x, y, and all results from f() {f()} -- creates a list with all results from f() {...} -- creates a list with all vararg parameters {f(), nil} -- f() is adjusted to 1 result \endpre \begp Any expression enclosed in parentheses always results in only one value. Thus, \begcode (f(x,y,z))\endcode is always a single value, even if \begcode f\endcode returns several values. (The value of \begcode (f(x,y,z))\endcode is the first value returned by \begcode f\endcode or {\bf nil} if \begcode f\endcode does not return any values.) \endp\subsubsection{Arithmetic Operators}\begp Lua supports the usual arithmetic operators: the binary \begcode +\endcode (addition), \begcode -\endcode (subtraction), \begcode *\endcode (multiplication), \begcode /\endcode (division), \begcode %\endcode (modulo), and \begcode ^\endcode (exponentiation); and unary \begcode -\endcode (negation). If the operands are numbers, or strings that can be converted to numbers (see %§2.2.1), then all operations have the usual meaning. Exponentiation works for any exponent. For instance, \begcode x^(-0.5)\endcode computes the inverse of the square root of \begcode x\endcode . Modulo is defined as \endp\begpre a % b == a - math.floor(a/b)*b \endpre \begp That is, it is the remainder of a division that rounds the quotient towards minus infinity. \endp\subsubsection{Relational Operators}\begp The relational operators in Lua are \endp\begpre == ~= < > <= >= \endpre \begp These operators always result in {\bf false} or {\bf true}. \endp\begp Equality (\begcode ==\endcode ) first compares the type of its operands. If the types are different, then the result is {\bf false}. Otherwise, the values of the operands are compared. Numbers and strings are compared in the usual way. Objects (tables, userdata, threads, and functions) are compared by {\em reference}: two objects are considered equal only if they are the {\em same} object. Every time you create a new object (a table, userdata, thread, or function), this new object is different from any previously existing object. \endp\begp You can change the way that Lua compares tables and userdata by using the "eq" metamethod (see %§2.8). \endp\begp The conversion rules of %§2.2.1 {\em do not} apply to equality comparisons. Thus, \begcode "0"==0\endcode evaluates to {\bf false}, and \begcode t[0]\endcode and \begcode t["0"]\endcode denote different entries in a table. \endp\begp The operator \begcode ~=\endcode is exactly the negation of equality (\begcode ==\endcode ). \endp\begp The order operators work as follows. If both arguments are numbers, then they are compared as such. Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Lua tries to call the "lt" or the "le" metamethod (see %§2.8). A comparison \begcode a > b\endcode is translated to \begcode b < a\endcode and \begcode a >= b\endcode is translated to \begcode b <= a\endcode . \endp\subsubsection{Logical Operators}\begp The logical operators in Lua are {\bf and}, {\bf or}, and {\bf not}. Like the control structures (see %§2.4.4), all logical operators consider both {\bf false} and {\bf nil} as false and anything else as true. \endp\begp The negation operator {\bf not} always returns {\bf false} or {\bf true}. The conjunction operator {\bf and} returns its first argument if this value is {\bf false} or {\bf nil}; otherwise, {\bf and} returns its second argument. The disjunction operator {\bf or} returns its first argument if this value is different from {\bf nil} and {\bf false}; otherwise, {\bf or} returns its second argument. Both {\bf and} and {\bf or} use short-cut evaluation; that is, the second operand is evaluated only if necessary. Here are some examples: \endp\begpre 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 \endpre \begp (In this manual, \begcode -->\endcode indicates the result of the preceding expression.) \endp\subsubsection{Concatenation}\begp The string concatenation operator in Lua is denoted by two dots ('\begcode ..\endcode '). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in %§2.2.1. Otherwise, the "concat" metamethod is called (see %§2.8). \endp\subsubsection{The Length Operator} \begp The length operator is denoted by the unary operator \begcode #\endcode . The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte). \endp\begp The length of a table \begcode t\endcode is defined to be any integer index \begcode n\endcode such that \begcode t[n]\endcode is not {\bf nil} and \begcode t[n+1]\endcode is {\bf nil}; moreover, if \begcode t[1]\endcode is {\bf nil}, \begcode n\endcode can be zero. For a regular array, with non-nil values from 1 to a given \begcode n\endcode , its length is exactly that \begcode n\endcode , the index of its last value. If the array has "holes" (that is, {\bf nil} values between other non-nil values), then \begcode #t\endcode can be any of the indices that directly precedes a {\bf nil} value (that is, it may consider any such {\bf nil} value as the end of the array). \endp\subsubsection{Precedence}\begp Operator precedence in Lua follows the table below, from lower to higher priority: \endp\begpre or and < > <= >= ~= == .. + - * / % not # - (unary) ^ \endpre \begp As usual, you can use parentheses to change the precedences of an expression. The concatenation ('\begcode ..\endcode ') and exponentiation ('\begcode ^\endcode ') operators are right associative. All other binary operators are left associative. \endp\subsubsection{Table Constructors}\begp Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is \endp\begpre tableconstructor ::= `{\bf {} [fieldlist] `{\bf }} fieldlist ::= field {fieldsep field} [fieldsep] field ::= `{\bf [} exp `{\bf ]} `{\bf =} exp | Name `{\bf =} exp | exp fieldsep ::= `{\bf ,} | `{\bf ;} \endpre \begp Each field of the form \begcode [exp1] = exp2\endcode adds to the new table an entry with key \begcode exp1\endcode and value \begcode exp2\endcode . A field of the form \begcode name = exp\endcode is equivalent to \begcode ["name"] = exp\endcode . Finally, fields of the form \begcode exp\endcode are equivalent to \begcode [i] = exp\endcode , where \begcode i\endcode are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. For example, \endp\begpre a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 } \endpre \begp is equivalent to \endp\begpre 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 \endpre \begp If the last field in the list has the form \begcode exp\endcode and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see %§2.5.8). To avoid this, enclose the function call or the vararg expression in parentheses (see %§2.5). \endp\begp The field list can have an optional trailing separator, as a convenience for machine-generated code. \endp\subsubsection{Function Calls}\begp A function call in Lua has the following syntax: \endp\begpre functioncall ::= prefixexp args \endpre \begp In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type {\em function}, then this function is called with the given arguments. Otherwise, the prefixexp "call" metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see %§2.8). \endp\begp The form \endp\begpre functioncall ::= prefixexp `{\bf :} Name args \endpre \begp can be used to call "methods". A call \begcode v:name({\em args})\endcode is syntactic sugar for \begcode v.name(v,{\em args})\endcode , except that \begcode v\endcode is evaluated only once. \endp\begp Arguments have the following syntax: \endp\begpre args ::= `{\bf (} [explist] `{\bf )} args ::= tableconstructor args ::= String \endpre \begp All argument expressions are evaluated before the call. A call of the form \begcode f{{\em fields}}\endcode is syntactic sugar for \begcode f({{\em fields}})\endcode ; that is, the argument list is a single new table. A call of the form \begcode f'{\em string}'\endcode (or \begcode f"{\em string}"\endcode or \begcode f[[{\em string}]]\endcode ) is syntactic sugar for \begcode f('{\em string}')\endcode ; that is, the argument list is a single literal string. \endp\begp As an exception to the free-format syntax of Lua, you cannot put a line break before the '\begcode (\endcode ' in a function call. This restriction avoids some ambiguities in the language. If you write \endp\begpre a = f (g).x(a) \endpre \begp Lua would see that as a single statement, \begcode a = f(g).x(a)\endcode . So, if you want two statements, you must add a semi-colon between them. If you actually want to call \begcode f\endcode , you must remove the line break before \begcode (g)\endcode . \endp\begp A call of the form \begcode return\endcode {\em functioncall} is called a {\em tail call}. Lua implements {\em proper tail calls} (or {\em proper tail recursion}): in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function. Note that a tail call only happens with a particular syntax, where the {\bf return} has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls: \endp\begpre return (f(x)) -- results adjusted to 1 return 2 * f(x) return x, f(x) -- additional results f(x); return -- results discarded return x or f(x) -- results adjusted to 1 \endpre \subsubsection{Function Definitions} \begp The syntax for function definition is \endp\begpre function ::= {\bf function} funcbody funcbody ::= `{\bf (} [parlist] `{\bf )} block {\bf end} \endpre \begp The following syntactic sugar simplifies function definitions: \endp\begpre stat ::= {\bf function} funcname funcbody stat ::= {\bf local} {\bf function} Name funcbody funcname ::= Name {`{\bf .} Name} [`{\bf :} Name] \endpre \begp The statement \endp\begpre function f () {\em body} end \endpre \begp translates to \endp\begpre f = function () {\em body} end \endpre \begp The statement \endp\begpre function t.a.b.c.f () {\em body} end \endpre \begp translates to \endp\begpre t.a.b.c.f = function () {\em body} end \endpre \begp The statement \endp\begpre local function f () {\em body} end \endpre \begp translates to \endp\begpre local f; f = function () {\em body} end \endpre \begp {\em not} to \endp\begpre local f = function () {\em body} end \endpre \begp (This only makes a difference when the body of the function contains references to \begcode f\endcode .) \endp\begp A function definition is an executable expression, whose value has type {\em function}. When Lua pre-compiles a chunk, all its function bodies are pre-compiled too. Then, whenever Lua executes the function definition, the function is {\em instantiated} (or {\em closed}). This function instance (or {\em closure}) is the final value of the expression. Different instances of the same function can refer to different external local variables and can have different environment tables. \endp\begp Parameters act as local variables that are initialized with the argument values: \endp\begpre parlist ::= namelist [`{\bf ,} `{\bf ...} ] | `{\bf ...} \endpre \begp When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a variadic or {\em vararg function}, which is indicated by three dots ('\begcode ...\endcode ') at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a {\em vararg expression}, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses). \endp\begp As an example, consider the following definitions: \endp\begpre function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end \endpre \begp Then, we have the following mapping from arguments to parameters and to the vararg expression: \endp\begpre CALL PARAMETERS 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, ... --> (nothing) g(3, 4) a=3, b=4, ... --> (nothing) g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 g(5, r()) a=5, b=1, ... --> 2 3 \endpre \begp Results are returned using the {\bf return} statement (see %§2.4.4). If control reaches the end of a function without encountering a {\bf return} statement, then the function returns with no results. \endp\begp The {\em colon} syntax is used for defining {\em methods}, that is, functions that have an implicit extra parameter \begcode self\endcode . Thus, the statement \endp\begpre function t.a.b.c:f ({\em params}) {\em body} end \endpre \begp is syntactic sugar for \endp\begpre t.a.b.c.f = function (self, {\em params}) {\em body} end \endpre \subsection{Visibility Rules} \begp Lua is a lexically scoped language. The scope of variables begins at the first statement {\em after} their declaration and lasts until the end of the innermost block that includes the declaration. Consider the following example: \endp\begpre x = 10 -- global variable do -- new block local x = x -- new 'x', with value 10 print(x) --> 10 x = x+1 do -- another block local x = x+1 -- another 'x' print(x) --> 12 end print(x) --> 11 end print(x) --> 10 (the global one) \endpre \begp Notice that, in a declaration like \begcode local x = x\endcode , the new \begcode x\endcode being declared is not in scope yet, and so the second \begcode x\endcode refers to the outside variable. \endp\begp Because of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. A local variable used by an inner function is called an {\em upvalue}, or {\em external local variable}, inside the inner function. \endp\begp Notice that each execution of a {\bf local} statement defines new local variables. Consider the following example: \endp\begpre a = {} local x = 20 for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y end end \endpre \begp The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different \begcode y\endcode variable, while all of them share the same \begcode x\endcode . \endp\subsection{Error Handling} \begp Because Lua is an embedded extension language, all Lua actions start from C~code in the host program calling a function from the Lua library (see %\begcode lua_pcall\endcode ). Whenever an error occurs during Lua compilation or execution, control returns to C, which can take appropriate measures (such as printing an error message). \endp\begp Lua code can explicitly generate an error by calling the %\begcode error\endcode function. If you need to catch errors in Lua, you can use the %\begcode pcall\endcode function. \endp\subsection{Metatables} \begp Every value in Lua can have a {\em metatable}. This {\em metatable} is an ordinary Lua table that defines the behavior of the original value under certain special operations. You can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. For instance, when a non-numeric value is the operand of an addition, Lua checks for a function in the field \begcode "__add"\endcode in its metatable. If it finds one, Lua calls this function to perform the addition. \endp\begp We call the keys in a metatable {\em events} and the values {\em metamethods}. In the previous example, the event is \begcode "add"\endcode and the metamethod is the function that performs the addition. \endp\begp You can query the metatable of any value through the %\begcode getmetatable\endcode function. \endp\begp You can replace the metatable of tables through the %\begcode setmetatable\endcode function. You cannot change the metatable of other types from Lua (except by using the debug library); you must use the C~API for that. \endp\begp Tables and full userdata have individual metatables (although multiple tables and userdata can share their metatables). Values of all other types share one single metatable per type; that is, there is one single metatable for all numbers, one for all strings, etc. \endp\begp A metatable controls how an object behaves in arithmetic operations, order comparisons, concatenation, length operation, and indexing. A metatable also can define a function to be called when a userdata is garbage collected. For each of these operations Lua associates a specific key called an {\em event}. When Lua performs one of these operations over a value, it checks whether this value has a metatable with the corresponding event. If so, the value associated with that key (the metamethod) controls how Lua will perform the operation. \endp\begp Metatables control the operations listed next. Each operation is identified by its corresponding name. The key for each operation is a string with its name prefixed by two underscores, '\begcode __\endcode '; for instance, the key for operation "add" is the string \begcode "__add"\endcode . The semantics of these operations is better explained by a Lua function describing how the interpreter executes the operation. \endp\begp The code shown here in Lua is only illustrative; the real behavior is hard coded in the interpreter and it is much more efficient than this simulation. All functions used in these descriptions (%\begcode rawget\endcode , %\begcode tonumber\endcode , etc.) are described in %§5.1. In particular, to retrieve the metamethod of a given object, we use the expression \endp\begpre metatable(obj)[event] \endpre \begp This should be read as \endp\begpre rawget(getmetatable(obj) or {}, event) \endpre \begp That is, the access to a metamethod does not invoke other metamethods, and the access to objects with no metatables does not fail (it simply results in {\bf nil}). \endp \subsection{Environments} \begp Besides metatables, objects of types thread, function, and userdata have another table associated with them, called their {\em environment}. Like metatables, environments are regular tables and multiple objects can share the same environment. \endp\begp Threads are created sharing the environment of the creating thread. Userdata and C~functions are created sharing the environment of the creating C~function. Non-nested Lua functions (created by %\begcode loadfile\endcode , %\begcode loadstring\endcode or %\begcode load\endcode ) are created sharing the environment of the creating thread. Nested Lua functions are created sharing the environment of the creating Lua function. \endp\begp Environments associated with userdata have no meaning for Lua. It is only a convenience feature for programmers to associate a table to a userdata. \endp\begp Environments associated with threads are called {\em global environments}. They are used as the default environment for threads and non-nested Lua functions created by the thread and can be directly accessed by C~code (see %§3.3). \endp\begp The environment associated with a C~function can be directly accessed by C~code (see %§3.3). It is used as the default environment for other C~functions and userdata created by the function. \endp\begp Environments associated with Lua functions are used to resolve all accesses to global variables within the function (see %§2.3). They are used as the default environment for nested Lua functions created by the function. \endp\begp You can change the environment of a Lua function or the running thread by calling %\begcode setfenv\endcode . You can get the environment of a Lua function or the running thread by calling %\begcode getfenv\endcode . To manipulate the environment of other objects (userdata, C~functions, other threads) you must use the C~API. \endp\subsection{Garbage Collection} \begp Lua performs automatic memory management. This means that you have to worry neither about allocating memory for new objects nor about freeing it when the objects are no longer needed. Lua manages memory automatically by running a {\em garbage collector} from time to time to collect all {\em dead objects} (that is, objects that are no longer accessible from Lua). All memory used by Lua is subject to automatic management: tables, userdata, functions, threads, strings, etc. \endp\begp Lua implements an incremental mark-and-sweep collector. It uses two numbers to control its garbage-collection cycles: the {\em garbage-collector pause} and the {\em garbage-collector step multiplier}. Both use percentage points as units (so that a value of 100 means an internal value of 1). \endp\begp The garbage-collector pause controls how long the collector waits before starting a new cycle. Larger values make the collector less aggressive. Values smaller than 100 mean the collector will not wait to start a new cycle. A value of 200 means that the collector waits for the total memory in use to double before starting a new cycle. \endp\begp The step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. Values smaller than 100 make the collector too slow and can result in the collector never finishing a cycle. The default, 200, means that the collector runs at "twice" the speed of memory allocation. \endp\begp You can change these numbers by calling %\begcode lua_gc\endcode in C or %\begcode collectgarbage\endcode in Lua. With these functions you can also control the collector directly (e.g., stop and restart it). \endp\subsubsection{Garbage-Collection Metamethods} \begp Using the C~API, you can set garbage-collector metamethods for userdata (see %§2.8). These metamethods are also called {\em finalizers}. Finalizers allow you to coordinate Lua's garbage collection with external resource management (such as closing files, network or database connections, or freeing your own memory). \endp\begp Garbage userdata with a field \begcode __gc\endcode in their metatables are not collected immediately by the garbage collector. Instead, Lua puts them in a list. After the collection, Lua does the equivalent of the following function for each userdata in that list: \endp\begpre function gc_event (udata) local h = metatable(udata).__gc if h then h(udata) end end \endpre \begp At the end of each garbage-collection cycle, the finalizers for userdata are called in {\em reverse} order of their creation, among those collected in that cycle. That is, the first finalizer to be called is the one associated with the userdata created last in the program. The userdata itself is freed only in the next garbage-collection cycle. \endp\subsubsection{Weak Tables} \begp A {\em weak table} is a table whose elements are {\em weak references}. A weak reference is ignored by the garbage collector. In other words, if the only references to an object are weak references, then the garbage collector will collect this object. \endp\begp A weak table can have weak keys, weak values, or both. A table with weak keys allows the collection of its keys, but prevents the collection of its values. A table with both weak keys and weak values allows the collection of both keys and values. In any case, if either the key or the value is collected, the whole pair is removed from the table. The weakness of a table is controlled by the \begcode __mode\endcode field of its metatable. If the \begcode __mode\endcode field is a string containing the character~'\begcode k\endcode ', the keys in the table are weak. If \begcode __mode\endcode contains '\begcode v\endcode ', the values in the table are weak. \endp\begp After you use a table as a metatable, you should not change the value of its \begcode __mode\endcode field. Otherwise, the weak behavior of the tables controlled by this metatable is undefined. \endp\subsection{Coroutines} \begp Lua supports coroutines, also called {\em collaborative multithreading}. A coroutine in Lua represents an independent thread of execution. Unlike threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. \endp\begp You create a coroutine with a call to %\begcode coroutine.create\endcode . Its sole argument is a function that is the main function of the coroutine. The \begcode create\endcode function only creates a new coroutine and returns a handle to it (an object of type {\em thread}); it does not start the coroutine execution. \endp\begp When you first call %\begcode coroutine.resume\endcode , passing as its first argument a thread returned by %\begcode coroutine.create\endcode , the coroutine starts its execution, at the first line of its main function. Extra arguments passed to %\begcode coroutine.resume\endcode are passed on to the coroutine main function. After the coroutine starts running, it runs until it terminates or {\em yields}. \endp\begp A coroutine can terminate its execution in two ways: normally, when its main function returns (explicitly or implicitly, after the last instruction); and abnormally, if there is an unprotected error. In the first case, %\begcode coroutine.resume\endcode returns {\bf true}, plus any values returned by the coroutine main function. In case of errors, %\begcode coroutine.resume\endcode returns {\bf false} plus an error message. \endp\begp A coroutine yields by calling %\begcode coroutine.yield\endcode . When a coroutine yields, the corresponding %\begcode coroutine.resume\endcode returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, %\begcode coroutine.resume\endcode also returns {\bf true}, plus any values passed to %\begcode coroutine.yield\endcode . The next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to %\begcode coroutine.yield\endcode returning any extra arguments passed to %\begcode coroutine.resume\endcode . \endp\begp Like %\begcode coroutine.create\endcode , the %\begcode coroutine.wrap\endcode function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to %\begcode coroutine.resume\endcode . %\begcode coroutine.wrap\endcode returns all the values returned by %\begcode coroutine.resume\endcode , except the first one (the boolean error code). Unlike %\begcode coroutine.resume\endcode , %\begcode coroutine.wrap\endcode does not catch errors; any error is propagated to the caller. \endp\begp As an example, consider the following code: \endp\begpre 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")) \endpre \begp When you run it, it produces the following output: \endp\begpre co-body 1 10 foo 2 main true 4 co-body r main true 11 -9 co-body x y main true 10 end main false cannot resume dead coroutine \endpre \begp \endp\section{The Application Program Interface} \begp This section describes the C~API for Lua, that is, the set of C~functions available to the host program to communicate with Lua. All API functions and related types and constants are declared in the header file \begcode lua.h\endcode. \endp\begp Even when we use the term "function", any facility in the API may be provided as a macro instead. All such macros use each of their arguments exactly once (except for the first argument, which is always a Lua state), and so do not generate any hidden side-effects. \endp\begp As in most C~libraries, the Lua API functions do not check their arguments for validity or consistency. However, you can change this behavior by compiling Lua with a proper definition for the macro \begcode luai_apicheck\endcode, in file \begcode luaconf.h\endcode . \endp\subsection{The Stack} \begp Lua uses a {\em virtual stack} to pass values to and from C. Each element in this stack represents a Lua value ({\bf nil}, number, string, etc.). \endp\begp Whenever Lua calls C, the called function gets a new stack, which is independent of previous stacks and of stacks of C~functions that are still active. This stack initially contains any arguments to the C~function and it is where the C~function pushes its results to be returned to the caller (see %\begcode lua_CFunction\endcode ). \endp\begp For convenience, most query operations in the API do not follow a strict stack discipline. Instead, they can refer to any element in the stack by using an {\em index}: A positive index represents an {\em absolute} stack position (starting at~1); a negative index represents an {\em offset} relative to the top of the stack. More specifically, if the stack has {\em n} elements, then index~1 represents the first element (that is, the element that was pushed onto the stack first) and index~{\em n} represents the last element; index~-1 also represents the last element (that is, the element at the~top) and index {\em -n} represents the first element. We say that an index is {\em valid} if it lies between~1 and the stack top (that is, if \begcode 1 ≤ abs(index) ≤ top\endcode ). \endp\subsection{Stack Size} \begp When you interact with Lua API, you are responsible for ensuring consistency. In particular, {\em you are responsible for controlling stack overflow}. You can use the function %\begcode lua_checkstack\endcode to grow the stack size. \endp\begp Whenever Lua calls C, it ensures that at least \begcode LUA_MINSTACK\endcode stack positions are available. \begcode LUA_MINSTACK\endcode is defined as 20, so that usually you do not have to worry about stack space unless your code has loops pushing elements onto the stack. \endp\begp Most query functions accept as indices any value inside the available stack space, that is, indices up to the maximum stack size you have set through %\begcode lua_checkstack\endcode . Such indices are called {\em acceptable indices}. More formally, we define an {\em acceptable index} as follows: \endp\begpre (index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace) \endpre \begp Note that 0 is never an acceptable index. \endp\subsection{Pseudo-Indices} \begp Unless otherwise noted, any function that accepts valid indices can also be called with {\em pseudo-indices}, which represent some Lua values that are accessible to C~code but which are not in the stack. Pseudo-indices are used to access the thread environment, the function environment, the registry, and the upvalues of a C~function (see %§3.4). \endp\begp The thread environment (where global variables live) is always at pseudo-index \begcode LUA_GLOBALSINDEX\endcode. The environment of the running C~function is always at pseudo-index \begcode LUA_ENVIRONINDEX\endcode. \endp\begp To access and change the value of global variables, you can use regular table operations over an environment table. For instance, to access the value of a global variable, do \endp\begpre lua_getfield(L, LUA_GLOBALSINDEX, varname); \endpre \subsection{C Closures} \begp When a C~function is created, it is possible to associate some values with it, thus creating a {\em C~closure}; these values are called {\em upvalues} and are accessible to the function whenever it is called (see %\begcode lua_pushcclosure\endcode ). \endp\begp Whenever a C~function is called, its upvalues are located at specific pseudo-indices. These pseudo-indices are produced by the macro \begcode lua_upvalueindex\endcode. The first value associated with a function is at position \begcode lua_upvalueindex(1)\endcode , and so on. Any access to \begcode lua_upvalueindex({\em n})\endcode , where {\em n} is greater than the number of upvalues of the current function (but not greater than 256), produces an acceptable (but invalid) index. \endp\subsection{Registry} \begp Lua provides a {\em registry}, a pre-defined table that can be used by any C~code to store whatever Lua value it needs to store. This table is always located at pseudo-index \begcode LUA_REGISTRYINDEX\endcode. Any C~library can store data into this table, but it should take care to choose keys different from those used by other libraries, to avoid collisions. Typically, you should use as key a string containing your library name or a light userdata with the address of a C~object in your code. \endp\begp The integer keys in the registry are used by the reference mechanism, implemented by the auxiliary library, and therefore should not be used for other purposes. \endp\subsection{Error Handling in C} \begp Internally, Lua uses the C \begcode longjmp\endcode facility to handle errors. (You can also choose to use exceptions if you use C++; see file \begcode luaconf.h\endcode .) When Lua faces any error (such as memory allocation errors, type errors, syntax errors, and runtime errors) it {\em raises} an error; that is, it does a long jump. A {\em protected environment} uses \begcode setjmp\endcode to set a recover point; any error jumps to the most recent active recover point. \endp\begp Most functions in the API can throw an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can throw errors. \endp\begp Inside a C~function you can throw an error by calling %\begcode lua_error\endcode . \subsection{3.7 - Functions and types} NED·LAT \endp\subsection{3.8 - The Debug Interface} \begp Lua has no built-in debugging facilities. Instead, it offers a special interface by means of functions and {\em hooks}. This interface allows the construction of different kinds of debuggers, profilers, and other tools that need "inside information" from the interpreter. \endp\hrule\subsubsection{\begcode lua_Debug\endcode } \begpre typedef struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) */ const char *what; /* (S) */ const char *source; /* (S) */ int currentline; /* (l) */ int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ {\em other fields} } lua_Debug;\endpre \begp A structure used to carry different pieces of information about an active function. %\begcode lua_getstack\endcode fills only the private part of this structure, for later use. To fill the other fields of %\begcode lua_Debug\endcode with useful information, call %\begcode lua_getinfo\endcode . \endp\begp The fields of %\begcode lua_Debug\endcode have the following meaning: \endp \hrule\subsubsection{\begcode lua_gethook\endcode }\begp [-0, +0, {\em -}] \endp\begpre lua_Hook lua_gethook (lua_State *L);\endpre \begp Returns the current hook function. \endp\hrule\subsubsection{\begcode lua_gethookcount\endcode }\begp [-0, +0, {\em -}] \endp\begpre int lua_gethookcount (lua_State *L);\endpre \begp Returns the current hook count. \endp\hrule\subsubsection{\begcode lua_gethookmask\endcode }\begp [-0, +0, {\em -}] \endp\begpre int lua_gethookmask (lua_State *L);\endpre \begp Returns the current hook mask. \endp\hrule\subsubsection{\begcode lua_getinfo\endcode }\begp [-(0|1), +(0|1|2), {\em m}] \endp\begpre int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);\endpre \begp Returns information about a specific function or function invocation. \endp\begp To get information about a function invocation, the parameter \begcode ar\endcode must be a valid activation record that was filled by a previous call to %\begcode lua_getstack\endcode or given as argument to a hook (see %\begcode lua_Hook\endcode ). \endp\begp To get information about a function you push it onto the stack and start the \begcode what\endcode string with the character '\begcode >\endcode '. (In that case, \begcode lua_getinfo\endcode pops the function in the top of the stack.) For instance, to know in which line a function \begcode f\endcode was defined, you can write the following code: \endp\begpre lua_Debug ar; lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */ lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined); \endpre \begp Each character in the string \begcode what\endcode selects some fields of the structure \begcode ar\endcode to be filled or a value to be pushed on the stack: \endp \begp This function returns 0 on error (for instance, an invalid option in \begcode what\endcode ). \endp\hrule\subsubsection{\begcode lua_getlocal\endcode }\begp [-0, +(0|1), {\em -}] \endp\begpre const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);\endpre \begp Gets information about a local variable of a given activation record. The parameter \begcode ar\endcode must be a valid activation record that was filled by a previous call to %\begcode lua_getstack\endcode or given as argument to a hook (see %\begcode lua_Hook\endcode ). The index \begcode n\endcode selects which local variable to inspect (1 is the first parameter or active local variable, and so on, until the last active local variable). %\begcode lua_getlocal\endcode pushes the variable's value onto the stack and returns its name. \endp\begp Variable names starting with '\begcode (\endcode ' (open parentheses) represent internal variables (loop control variables, temporaries, and C~function locals). \endp\begp Returns \begcode NULL\endcode (and pushes nothing) when the index is greater than the number of active local variables. \endp\hrule\subsubsection{\begcode lua_getstack\endcode }\begp [-0, +0, {\em -}] \endp\begpre int lua_getstack (lua_State *L, int level, lua_Debug *ar);\endpre \begp Get information about the interpreter runtime stack. \endp\begp This function fills parts of a %\begcode lua_Debug\endcode structure with an identification of the {\em activation record} of the function executing at a given level. Level~0 is the current running function, whereas level {\em n+1} is the function that has called level {\em n}. When there are no errors, %\begcode lua_getstack\endcode returns 1; when called with a level greater than the stack depth, it returns 0. \endp\hrule\subsubsection{\begcode lua_getupvalue\endcode }\begp [-0, +(0|1), {\em -}] \endp\begpre const char *lua_getupvalue (lua_State *L, int funcindex, int n);\endpre \begp Gets information about a closure's upvalue. (For Lua functions, upvalues are the external local variables that the function uses, and that are consequently included in its closure.) %\begcode lua_getupvalue\endcode gets the index \begcode n\endcode of an upvalue, pushes the upvalue's value onto the stack, and returns its name. \begcode funcindex\endcode points to the closure in the stack. (Upvalues have no particular order, as they are active through the whole function. So, they are numbered in an arbitrary order.) \endp\begp Returns \begcode NULL\endcode (and pushes nothing) when the index is greater than the number of upvalues. For C~functions, this function uses the empty string \begcode ""\endcode as a name for all upvalues. \endp\hrule\subsubsection{\begcode lua_Hook\endcode } \begpre typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);\endpre \begp Type for debugging hook functions. \endp\begp Whenever a hook is called, its \begcode ar\endcode argument has its field \begcode event\endcode set to the specific event that triggered the hook. Lua identifies these events with the following constants: \begcode LUA_HOOKCALL\endcode , \begcode LUA_HOOKRET\endcode , \begcode LUA_HOOKTAILRET\endcode , \begcode LUA_HOOKLINE\endcode , and \begcode LUA_HOOKCOUNT\endcode . Moreover, for line events, the field \begcode currentline\endcode is also set. To get the value of any other field in \begcode ar\endcode , the hook must call %\begcode lua_getinfo\endcode . For return events, \begcode event\endcode can be \begcode LUA_HOOKRET\endcode , the normal value, or \begcode LUA_HOOKTAILRET\endcode . In the latter case, Lua is simulating a return from a function that did a tail call; in this case, it is useless to call %\begcode lua_getinfo\endcode . \endp\begp While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls back Lua to execute a function or a chunk, this execution occurs without any calls to hooks. \endp\hrule\subsubsection{\begcode lua_sethook\endcode }\begp [-0, +0, {\em -}] \endp\begpre int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);\endpre \begp Sets the debugging hook function. \endp\begp Argument \begcode f\endcode is the hook function. \begcode mask\endcode specifies on which events the hook will be called: it is formed by a bitwise or of the constants \begcode LUA_MASKCALL\endcode , \begcode LUA_MASKRET\endcode , \begcode LUA_MASKLINE\endcode , and \begcode LUA_MASKCOUNT\endcode . The \begcode count\endcode argument is only meaningful when the mask includes \begcode LUA_MASKCOUNT\endcode . For each event, the hook is called as explained below: \endp \begp A hook is disabled by setting \begcode mask\endcode to zero. \endp\hrule\subsubsection{\begcode lua_setlocal\endcode }\begp [-(0|1), +0, {\em -}] \endp\begpre const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);\endpre \begp Sets the value of a local variable of a given activation record. Parameters \begcode ar\endcode and \begcode n\endcode are as in %\begcode lua_getlocal\endcode (see %\begcode lua_getlocal\endcode ). %\begcode lua_setlocal\endcode assigns the value at the top of the stack to the variable and returns its name. It also pops the value from the stack. \endp\begp Returns \begcode NULL\endcode (and pops nothing) when the index is greater than the number of active local variables. \endp\hrule\subsubsection{\begcode lua_setupvalue\endcode }\begp [-(0|1), +0, {\em -}] \endp\begpre const char *lua_setupvalue (lua_State *L, int funcindex, int n);\endpre \begp Sets the value of a closure's upvalue. It assigns the value at the top of the stack to the upvalue and returns its name. It also pops the value from the stack. Parameters \begcode funcindex\endcode and \begcode n\endcode are as in the %\begcode lua_getupvalue\endcode (see %\begcode lua_getupvalue\endcode ). \endp\begp Returns \begcode NULL\endcode (and pops nothing) when the index is greater than the number of upvalues. \endp\section{4 - The Auxiliary Library} \begp The {\em auxiliary library} provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks. \endp\begp All functions from the auxiliary library are defined in header file \begcode lauxlib.h\endcode and have a prefix \begcode luaL_\endcode . \endp\begp All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with this API. \endp\begp Several functions in the auxiliary library are used to check C~function arguments. Their names are always \begcode luaL_check*\endcode or \begcode luaL_opt*\endcode . All of these functions throw an error if the check is not satisfied. Because the error message is formatted for arguments (e.g., "\begcode bad argument #1\endcode "), you should not use these functions for other stack values. \endp\subsection{4.1 - Functions and Types} \begp Here we list all functions and types from the auxiliary library in alphabetical order. \endp\hrule\subsubsection{\begcode luaL_addchar\endcode }\begp [-0, +0, {\em m}] \endp\begpre void luaL_addchar (luaL_Buffer *B, char c);\endpre \begp Adds the character \begcode c\endcode to the buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ). \endp\hrule\subsubsection{\begcode luaL_addlstring\endcode }\begp [-0, +0, {\em m}] \endp\begpre void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);\endpre \begp Adds the string pointed to by \begcode s\endcode with length \begcode l\endcode to the buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ). The string may contain embedded zeros. \endp\hrule\subsubsection{\begcode luaL_addsize\endcode }\begp [-0, +0, {\em m}] \endp\begpre void luaL_addsize (luaL_Buffer *B, size_t n);\endpre \begp Adds to the buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ) a string of length \begcode n\endcode previously copied to the buffer area (see %\begcode luaL_prepbuffer\endcode ). \endp\hrule\subsubsection{\begcode luaL_addstring\endcode }\begp [-0, +0, {\em m}] \endp\begpre void luaL_addstring (luaL_Buffer *B, const char *s);\endpre \begp Adds the zero-terminated string pointed to by \begcode s\endcode to the buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ). The string may not contain embedded zeros. \endp\hrule\subsubsection{\begcode luaL_addvalue\endcode }\begp [-1, +0, {\em m}] \endp\begpre void luaL_addvalue (luaL_Buffer *B);\endpre \begp Adds the value at the top of the stack to the buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ). Pops the value. \endp\begp This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer. \endp\hrule\subsubsection{\begcode luaL_argcheck\endcode }\begp [-0, +0, {\em v}] \endp\begpre void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);\endpre \begp Checks whether \begcode cond\endcode is true. If not, raises an error with the following message, where \begcode func\endcode is retrieved from the call stack: \endp\begpre bad argument # to () \endpre \hrule\subsubsection{\begcode luaL_argerror\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_argerror (lua_State *L, int narg, const char *extramsg);\endpre \begp Raises an error with the following message, where \begcode func\endcode is retrieved from the call stack: \endp\begpre bad argument # to () \endpre \begp This function never returns, but it is an idiom to use it in C~functions as \begcode return luaL_argerror({\em args})\endcode . \endp\hrule\subsubsection{\begcode luaL_Buffer\endcode } \begpre typedef struct luaL_Buffer luaL_Buffer;\endpre \begp Type for a {\em string buffer}. \endp\begp A string buffer allows C~code to build Lua strings piecemeal. Its pattern of use is as follows: \endp
  • First you declare a variable \begcode b\endcode of type %\begcode luaL_Buffer\endcode .
  • Then you initialize it with a call \begcode luaL_buffinit(L, &b)\endcode .
  • Then you add string pieces to the buffer calling any of the \begcode luaL_add*\endcode functions.
  • You finish by calling \begcode luaL_pushresult(&b)\endcode . This call leaves the final string on the top of the stack.
\begp During its normal operation, a string buffer uses a variable number of stack slots. So, while using a buffer, you cannot assume that you know where the top of the stack is. You can use the stack between successive calls to buffer operations as long as that use is balanced; that is, when you call a buffer operation, the stack is at the same level it was immediately after the previous buffer operation. (The only exception to this rule is %\begcode luaL_addvalue\endcode .) After calling %\begcode luaL_pushresult\endcode the stack is back to its level when the buffer was initialized, plus the final string on its top. \endp\hrule\subsubsection{\begcode luaL_buffinit\endcode }\begp [-0, +0, {\em e}] \endp\begpre void luaL_buffinit (lua_State *L, luaL_Buffer *B);\endpre \begp Initializes a buffer \begcode B\endcode . This function does not allocate any space; the buffer must be declared as a variable (see %\begcode luaL_Buffer\endcode ). \endp\hrule\subsubsection{\begcode luaL_callmeta\endcode }\begp [-0, +(0|1), {\em e}] \endp\begpre int luaL_callmeta (lua_State *L, int obj, const char *e);\endpre \begp Calls a metamethod. \endp\begp If the object at index \begcode obj\endcode has a metatable and this metatable has a field \begcode e\endcode , this function calls this field and passes the object as its only argument. In this case this function returns 1 and pushes onto the stack the value returned by the call. If there is no metatable or no metamethod, this function returns 0 (without pushing any value on the stack). \endp\hrule\subsubsection{\begcode luaL_checkany\endcode }\begp [-0, +0, {\em v}] \endp\begpre void luaL_checkany (lua_State *L, int narg);\endpre \begp Checks whether the function has an argument of any type (including {\bf nil}) at position \begcode narg\endcode . \endp\hrule\subsubsection{\begcode luaL_checkint\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_checkint (lua_State *L, int narg);\endpre \begp Checks whether the function argument \begcode narg\endcode is a number and returns this number cast to an \begcode int\endcode . \endp\hrule\subsubsection{\begcode luaL_checkinteger\endcode }\begp [-0, +0, {\em v}] \endp\begpre lua_Integer luaL_checkinteger (lua_State *L, int narg);\endpre \begp Checks whether the function argument \begcode narg\endcode is a number and returns this number cast to a %\begcode lua_Integer\endcode . \endp\hrule\subsubsection{\begcode luaL_checklong\endcode }\begp [-0, +0, {\em v}] \endp\begpre long luaL_checklong (lua_State *L, int narg);\endpre \begp Checks whether the function argument \begcode narg\endcode is a number and returns this number cast to a \begcode long\endcode . \endp\hrule\subsubsection{\begcode luaL_checklstring\endcode }\begp [-0, +0, {\em v}] \endp\begpre const char *luaL_checklstring (lua_State *L, int narg, size_t *l);\endpre \begp Checks whether the function argument \begcode narg\endcode is a string and returns this string; if \begcode l\endcode is not \begcode NULL\endcode fills \begcode *l\endcode with the string's length. \endp\begp This function uses %\begcode lua_tolstring\endcode to get its result, so all conversions and caveats of that function apply here. \endp\hrule\subsubsection{\begcode luaL_checknumber\endcode }\begp [-0, +0, {\em v}] \endp\begpre lua_Number luaL_checknumber (lua_State *L, int narg);\endpre \begp Checks whether the function argument \begcode narg\endcode is a number and returns this number. \endp\hrule\subsubsection{\begcode luaL_checkoption\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]);\endpre \begp Checks whether the function argument \begcode narg\endcode is a string and searches for this string in the array \begcode lst\endcode (which must be NULL-terminated). Returns the index in the array where the string was found. Raises an error if the argument is not a string or if the string cannot be found. \endp\begp If \begcode def\endcode is not \begcode NULL\endcode , the function uses \begcode def\endcode as a default value when there is no argument \begcode narg\endcode or if this argument is {\bf nil}. \endp\begp This is a useful function for mapping strings to C~enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.) \endp\hrule\subsubsection{\begcode luaL_checkstack\endcode }\begp [-0, +0, {\em v}] \endp\begpre void luaL_checkstack (lua_State *L, int sz, const char *msg);\endpre \begp Grows the stack size to \begcode top + sz\endcode elements, raising an error if the stack cannot grow to that size. \begcode msg\endcode is an additional text to go into the error message. \endp\hrule\subsubsection{\begcode luaL_checkstring\endcode }\begp [-0, +0, {\em v}] \endp\begpre const char *luaL_checkstring (lua_State *L, int narg);\endpre \begp Checks whether the function argument \begcode narg\endcode is a string and returns this string. \endp\begp This function uses %\begcode lua_tolstring\endcode to get its result, so all conversions and caveats of that function apply here. \endp\hrule\subsubsection{\begcode luaL_checktype\endcode }\begp [-0, +0, {\em v}] \endp\begpre void luaL_checktype (lua_State *L, int narg, int t);\endpre \begp Checks whether the function argument \begcode narg\endcode has type \begcode t\endcode . See %\begcode lua_type\endcode for the encoding of types for \begcode t\endcode . \endp\hrule\subsubsection{\begcode luaL_checkudata\endcode }\begp [-0, +0, {\em v}] \endp\begpre void *luaL_checkudata (lua_State *L, int narg, const char *tname);\endpre \begp Checks whether the function argument \begcode narg\endcode is a userdata of the type \begcode tname\endcode (see %\begcode luaL_newmetatable\endcode ). \endp\hrule\subsubsection{\begcode luaL_dofile\endcode }\begp [-0, +?, {\em m}] \endp\begpre int luaL_dofile (lua_State *L, const char *filename);\endpre \begp Loads and runs the given file. It is defined as the following macro: \endp\begpre (luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0)) \endpre \begp It returns 0 if there are no errors or 1 in case of errors. \endp\hrule\subsubsection{\begcode luaL_dostring\endcode }\begp [-0, +?, {\em m}] \endp\begpre int luaL_dostring (lua_State *L, const char *str);\endpre \begp Loads and runs the given string. It is defined as the following macro: \endp\begpre (luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0)) \endpre \begp It returns 0 if there are no errors or 1 in case of errors. \endp\hrule\subsubsection{\begcode luaL_error\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_error (lua_State *L, const char *fmt, ...);\endpre \begp Raises an error. The error message format is given by \begcode fmt\endcode plus any extra arguments, following the same rules of %\begcode lua_pushfstring\endcode . It also adds at the beginning of the message the file name and the line number where the error occurred, if this information is available. \endp\begp This function never returns, but it is an idiom to use it in C~functions as \begcode return luaL_error({\em args})\endcode . \endp\hrule\subsubsection{\begcode luaL_getmetafield\endcode }\begp [-0, +(0|1), {\em m}] \endp\begpre int luaL_getmetafield (lua_State *L, int obj, const char *e);\endpre \begp Pushes onto the stack the field \begcode e\endcode from the metatable of the object at index \begcode obj\endcode . If the object does not have a metatable, or if the metatable does not have this field, returns 0 and pushes nothing. \endp\hrule\subsubsection{\begcode luaL_getmetatable\endcode }\begp [-0, +1, {\em -}] \endp\begpre void luaL_getmetatable (lua_State *L, const char *tname);\endpre \begp Pushes onto the stack the metatable associated with name \begcode tname\endcode in the registry (see %\begcode luaL_newmetatable\endcode ). \endp\hrule\subsubsection{\begcode luaL_gsub\endcode }\begp [-0, +1, {\em m}] \endp\begpre const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r);\endpre \begp Creates a copy of string \begcode s\endcode by replacing any occurrence of the string \begcode p\endcode with the string \begcode r\endcode . Pushes the resulting string on the stack and returns it. \endp\hrule\subsubsection{\begcode luaL_loadbuffer\endcode }\begp [-0, +1, {\em m}] \endp\begpre int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);\endpre \begp Loads a buffer as a Lua chunk. This function uses %\begcode lua_load\endcode to load the chunk in the buffer pointed to by \begcode buff\endcode with size \begcode sz\endcode . \endp\begp This function returns the same results as %\begcode lua_load\endcode . \begcode name\endcode is the chunk name, used for debug information and error messages. \endp\hrule\subsubsection{\begcode luaL_loadfile\endcode }\begp [-0, +1, {\em m}] \endp\begpre int luaL_loadfile (lua_State *L, const char *filename);\endpre \begp Loads a file as a Lua chunk. This function uses %\begcode lua_load\endcode to load the chunk in the file named \begcode filename\endcode . If \begcode filename\endcode is \begcode NULL\endcode , then it loads from the standard input. The first line in the file is ignored if it starts with a \begcode #\endcode . \endp\begp This function returns the same results as %\begcode lua_load\endcode , but it has an extra error code \begcode LUA_ERRFILE\endcode if it cannot open/read the file. \endp\begp As %\begcode lua_load\endcode , this function only loads the chunk; it does not run it. \endp\hrule\subsubsection{\begcode luaL_loadstring\endcode }\begp [-0, +1, {\em m}] \endp\begpre int luaL_loadstring (lua_State *L, const char *s);\endpre \begp Loads a string as a Lua chunk. This function uses %\begcode lua_load\endcode to load the chunk in the zero-terminated string \begcode s\endcode . \endp\begp This function returns the same results as %\begcode lua_load\endcode . \endp\begp Also as %\begcode lua_load\endcode , this function only loads the chunk; it does not run it. \endp\hrule\subsubsection{\begcode luaL_newmetatable\endcode }\begp [-0, +1, {\em m}] \endp\begpre int luaL_newmetatable (lua_State *L, const char *tname);\endpre \begp If the registry already has the key \begcode tname\endcode , returns 0. Otherwise, creates a new table to be used as a metatable for userdata, adds it to the registry with key \begcode tname\endcode , and returns 1. \endp\begp In both cases pushes onto the stack the final value associated with \begcode tname\endcode in the registry. \endp\hrule\subsubsection{\begcode luaL_newstate\endcode }\begp [-0, +0, {\em -}] \endp\begpre lua_State *luaL_newstate (void);\endpre \begp Creates a new Lua state. It calls %\begcode lua_newstate\endcode with an allocator based on the standard~C \begcode realloc\endcode function and then sets a panic function (see %\begcode lua_atpanic\endcode ) that prints an error message to the standard error output in case of fatal errors. \endp\begp Returns the new state, or \begcode NULL\endcode if there is a memory allocation error. \endp\hrule\subsubsection{\begcode luaL_openlibs\endcode }\begp [-0, +0, {\em m}] \endp\begpre void luaL_openlibs (lua_State *L);\endpre \begp Opens all standard Lua libraries into the given state. \endp\hrule\subsubsection{\begcode luaL_optint\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_optint (lua_State *L, int narg, int d);\endpre \begp If the function argument \begcode narg\endcode is a number, returns this number cast to an \begcode int\endcode . If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\hrule\subsubsection{\begcode luaL_optinteger\endcode }\begp [-0, +0, {\em v}] \endp\begpre lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);\endpre \begp If the function argument \begcode narg\endcode is a number, returns this number cast to a %\begcode lua_Integer\endcode . If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\hrule\subsubsection{\begcode luaL_optlong\endcode }\begp [-0, +0, {\em v}] \endp\begpre long luaL_optlong (lua_State *L, int narg, long d);\endpre \begp If the function argument \begcode narg\endcode is a number, returns this number cast to a \begcode long\endcode . If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\hrule\subsubsection{\begcode luaL_optlstring\endcode }\begp [-0, +0, {\em v}] \endp\begpre const char *luaL_optlstring (lua_State *L, int narg, const char *d, size_t *l);\endpre \begp If the function argument \begcode narg\endcode is a string, returns this string. If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\begp If \begcode l\endcode is not \begcode NULL\endcode , fills the position \begcode *l\endcode with the results's length. \endp\hrule\subsubsection{\begcode luaL_optnumber\endcode }\begp [-0, +0, {\em v}] \endp\begpre lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);\endpre \begp If the function argument \begcode narg\endcode is a number, returns this number. If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\hrule\subsubsection{\begcode luaL_optstring\endcode }\begp [-0, +0, {\em v}] \endp\begpre const char *luaL_optstring (lua_State *L, int narg, const char *d);\endpre \begp If the function argument \begcode narg\endcode is a string, returns this string. If this argument is absent or is {\bf nil}, returns \begcode d\endcode . Otherwise, raises an error. \endp\hrule\subsubsection{\begcode luaL_prepbuffer\endcode }\begp [-0, +0, {\em -}] \endp\begpre char *luaL_prepbuffer (luaL_Buffer *B);\endpre \begp Returns an address to a space of size \begcode LUAL_BUFFERSIZE\endcode where you can copy a string to be added to buffer \begcode B\endcode (see %\begcode luaL_Buffer\endcode ). After copying the string into this space you must call %\begcode luaL_addsize\endcode with the size of the string to actually add it to the buffer. \endp\hrule\subsubsection{\begcode luaL_pushresult\endcode }\begp [-?, +1, {\em m}] \endp\begpre void luaL_pushresult (luaL_Buffer *B);\endpre \begp Finishes the use of buffer \begcode B\endcode leaving the final string on the top of the stack. \endp\hrule\subsubsection{\begcode luaL_ref\endcode }\begp [-1, +0, {\em m}] \endp\begpre int luaL_ref (lua_State *L, int t);\endpre \begp Creates and returns a {\em reference}, in the table at index \begcode t\endcode , for the object at the top of the stack (and pops the object). \endp\begp A reference is a unique integer key. As long as you do not manually add integer keys into table \begcode t\endcode , %\begcode luaL_ref\endcode ensures the uniqueness of the key it returns. You can retrieve an object referred by reference \begcode r\endcode by calling \begcode lua_rawgeti(L, t, r)\endcode . Function %\begcode luaL_unref\endcode frees a reference and its associated object. \endp\begp If the object at the top of the stack is {\bf nil}, %\begcode luaL_ref\endcode returns the constant \begcode LUA_REFNIL\endcode . The constant \begcode LUA_NOREF\endcode is guaranteed to be different from any reference returned by %\begcode luaL_ref\endcode . \endp\hrule\subsubsection{\begcode luaL_Reg\endcode } \begpre typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg;\endpre \begp Type for arrays of functions to be registered by %\begcode luaL_register\endcode . \begcode name\endcode is the function name and \begcode func\endcode is a pointer to the function. Any array of %\begcode luaL_Reg\endcode must end with an sentinel entry in which both \begcode name\endcode and \begcode func\endcode are \begcode NULL\endcode . \endp\hrule\subsubsection{\begcode luaL_register\endcode }\begp [-(0|1), +1, {\em m}] \endp\begpre void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l);\endpre \begp Opens a library. \endp\begp When called with \begcode libname\endcode equal to \begcode NULL\endcode , it simply registers all functions in the list \begcode l\endcode (see %\begcode luaL_Reg\endcode ) into the table on the top of the stack. \endp\begp When called with a non-null \begcode libname\endcode , \begcode luaL_register\endcode creates a new table \begcode t\endcode , sets it as the value of the global variable \begcode libname\endcode , sets it as the value of \begcode package.loaded[libname]\endcode , and registers on it all functions in the list \begcode l\endcode . If there is a table in \begcode package.loaded[libname]\endcode or in variable \begcode libname\endcode , reuses this table instead of creating a new one. \endp\begp In any case the function leaves the table on the top of the stack. \endp\hrule\subsubsection{\begcode luaL_typename\endcode }\begp [-0, +0, {\em -}] \endp\begpre const char *luaL_typename (lua_State *L, int index);\endpre \begp Returns the name of the type of the value at the given index. \endp\hrule\subsubsection{\begcode luaL_typerror\endcode }\begp [-0, +0, {\em v}] \endp\begpre int luaL_typerror (lua_State *L, int narg, const char *tname);\endpre \begp Generates an error with a message like the following: \endp\begpre {\em location}: bad argument {\em narg} to '{\em func}' ({\em tname} expected, got {\em rt}) \endpre \begp where \begcode {\em location}\endcode is produced by %\begcode luaL_where\endcode , \begcode {\em func}\endcode is the name of the current function, and \begcode {\em rt}\endcode is the type name of the actual argument. \endp\hrule\subsubsection{\begcode luaL_unref\endcode }\begp [-0, +0, {\em -}] \endp\begpre void luaL_unref (lua_State *L, int t, int ref);\endpre \begp Releases reference \begcode ref\endcode from the table at index \begcode t\endcode (see %\begcode luaL_ref\endcode ). The entry is removed from the table, so that the referred object can be collected. The reference \begcode ref\endcode is also freed to be used again. \endp\begp If \begcode ref\endcode is %\begcode LUA_NOREF\endcode or %\begcode LUA_REFNIL\endcode , %\begcode luaL_unref\endcode does nothing. \endp\hrule\subsubsection{\begcode luaL_where\endcode }\begp [-0, +1, {\em m}] \endp\begpre void luaL_where (lua_State *L, int lvl);\endpre \begp Pushes onto the stack a string identifying the current position of the control at level \begcode lvl\endcode in the call stack. Typically this string has the following format: \endp\begpre {\em chunkname}:{\em currentline}: \endpre \begp Level~0 is the running function, level~1 is the function that called the running function, etc. \endp\begp This function is used to build a prefix for error messages. \endp\section{5 - Standard Libraries} \begp The standard Lua libraries provide useful functions that are implemented directly through the C~API. Some of these functions provide essential services to the language (e.g., %\begcode type\endcode and %\begcode getmetatable\endcode ); others provide access to "outside" services (e.g., I/O); and others could be implemented in Lua itself, but are quite useful or have critical performance requirements that deserve an implementation in C (e.g., %\begcode table.sort\endcode ). \endp\begp All libraries are implemented through the official C~API and are provided as separate C~modules. Currently, Lua has the following standard libraries: \endp
  • basic library, which includes the coroutine sub-library;
  • package library;
  • string manipulation;
  • table manipulation;
  • mathematical functions (sin, log, etc.);
  • input and output;
  • operating system facilities;
  • debug facilities.
\begp Except for the basic and package libraries, each library provides all its functions as fields of a global table or as methods of its objects. \endp\begp To have access to these libraries, the C~host program should call the %\begcode luaL_openlibs\endcode function, which opens all standard libraries. Alternatively, it can open them individually by calling \begcode luaopen_base\endcode (for the basic library), \begcode luaopen_package\endcode (for the package library), \begcode luaopen_string\endcode (for the string library), \begcode luaopen_table\endcode (for the table library), \begcode luaopen_math\endcode (for the mathematical library), \begcode luaopen_io\endcode (for the I/O library), \begcode luaopen_os\endcode (for the Operating System library), and \begcode luaopen_debug\endcode (for the debug library). These functions are declared in \begcode lualib.h\endcode and should not be called directly: you must call them like any other Lua C~function, e.g., by using %\begcode lua_call\endcode . \endp\subsection{5.1 - Basic Functions} \begp The basic library provides some core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities. \endp\begp \endp\hrule\subsubsection{\begcode assert (v [, message])\endcode } Issues an error when the value of its argument \begcode v\endcode is false (i.e., {\bf nil} or {\bf false}); otherwise, returns all its arguments. \begcode message\endcode is an error message; when absent, it defaults to "assertion failed!" \begp \endp\hrule\subsubsection{\begcode collectgarbage (opt [, arg])\endcode } \begp This function is a generic interface to the garbage collector. It performs different functions according to its first argument, \begcode opt\endcode : \endp
  • {\bf "stop":} stops the garbage collector.
  • {\bf "restart":} restarts the garbage collector.
  • {\bf "collect":} performs a full garbage-collection cycle.
  • {\bf "count":} returns the total memory in use by Lua (in Kbytes).
  • {\bf "step":} performs a garbage-collection step. The step "size" is controlled by \begcode arg\endcode (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of \begcode arg\endcode . Returns {\bf true} if the step finished a collection cycle.
  • {\bf "setpause":} sets \begcode arg\endcode as the new value for the {\em pause} of the collector (see %§2.10). Returns the previous value for {\em pause}.
  • {\bf "setstepmul":} sets \begcode arg\endcode as the new value for the {\em step multiplier} of the collector (see %§2.10). Returns the previous value for {\em step}.
\begp \endp\hrule\subsubsection{\begcode dofile (filename)\endcode } Opens the named file and executes its contents as a Lua chunk. When called without arguments, \begcode dofile\endcode executes the contents of the standard input (\begcode stdin\endcode ). Returns all values returned by the chunk. In case of errors, \begcode dofile\endcode propagates the error to its caller (that is, \begcode dofile\endcode does not run in protected mode). \begp \endp\hrule\subsubsection{\begcode error (message [, level])\endcode } Terminates the last protected function called and returns \begcode message\endcode as the error message. Function \begcode error\endcode never returns. \begp Usually, \begcode error\endcode adds some information about the error position at the beginning of the message. The \begcode level\endcode argument specifies how to get the error position. With level~1 (the default), the error position is where the \begcode error\endcode function was called. Level~2 points the error to where the function that called \begcode error\endcode was called; and so on. Passing a level~0 avoids the addition of error position information to the message. \endp\begp \endp\hrule\subsubsection{\begcode _G\endcode } A global variable (not a function) that holds the global environment (that is, \begcode _G._G = _G\endcode ). Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa. (Use %\begcode setfenv\endcode to change environments.) \begp \endp\hrule\subsubsection{\begcode getfenv ([f])\endcode } Returns the current environment in use by the function. \begcode f\endcode can be a Lua function or a number that specifies the function at that stack level: Level~1 is the function calling \begcode getfenv\endcode . If the given function is not a Lua function, or if \begcode f\endcode is 0, \begcode getfenv\endcode returns the global environment. The default for \begcode f\endcode is 1. \begp \endp\hrule\subsubsection{\begcode getmetatable (object)\endcode } \begp If \begcode object\endcode does not have a metatable, returns {\bf nil}. Otherwise, if the object's metatable has a \begcode "__metatable"\endcode field, returns the associated value. Otherwise, returns the metatable of the given object. \endp\begp \endp\hrule\subsubsection{\begcode ipairs (t)\endcode } \begp Returns three values: an iterator function, the table \begcode t\endcode , and 0, so that the construction \endp\begpre for i,v in ipairs(t) do {\em body} end \endpre \begp will iterate over the pairs (\begcode 1,t[1]\endcode ), (\begcode 2,t[2]\endcode ), %·%·%·, up to the first integer key absent from the table. \endp\begp \endp\hrule\subsubsection{\begcode load (func [, chunkname])\endcode } \begp Loads a chunk using function \begcode func\endcode to get its pieces. Each call to \begcode func\endcode must return a string that concatenates with previous results. A return of an empty string, {\bf nil}, or no value signals the end of the chunk. \endp\begp If there are no errors, returns the compiled chunk as a function; otherwise, returns {\bf nil} plus the error message. The environment of the returned function is the global environment. \endp\begp \begcode chunkname\endcode is used as the chunk name for error messages and debug information. When absent, it defaults to "\begcode =(load)\endcode ". \endp\begp \endp\hrule\subsubsection{\begcode loadfile ([filename])\endcode } \begp Similar to %\begcode load\endcode , but gets the chunk from file \begcode filename\endcode or from the standard input, if no file name is given. \endp\begp \endp\hrule\subsubsection{\begcode loadstring (string [, chunkname])\endcode } \begp Similar to %\begcode load\endcode , but gets the chunk from the given string. \endp\begp To load and run a given string, use the idiom \endp\begpre assert(loadstring(s))() \endpre \begp When absent, \begcode chunkname\endcode defaults to the given string. \endp\begp \endp\hrule\subsubsection{\begcode next (table [, index])\endcode } \begp Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. \begcode next\endcode returns the next index of the table and its associated value. When called with {\bf nil} as its second argument, \begcode next\endcode returns an initial index and its associated value. When called with the last index, or with {\bf nil} in an empty table, \begcode next\endcode returns {\bf nil}. If the second argument is absent, then it is interpreted as {\bf nil}. In particular, you can use \begcode next(t)\endcode to check whether a table is empty. \endp\begp The order in which the indices are enumerated is not specified, {\em even for numeric indices}. (To traverse a table in numeric order, use a numerical {\bf for} or the %\begcode ipairs\endcode function.) \endp\begp The behavior of \begcode next\endcode is {\em undefined} if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields. \endp\begp \endp\hrule\subsubsection{\begcode pairs (t)\endcode } \begp Returns three values: the %\begcode next\endcode function, the table \begcode t\endcode , and {\bf nil}, so that the construction \endp\begpre for k,v in pairs(t) do {\em body} end \endpre \begp will iterate over all key–value pairs of table \begcode t\endcode . \endp\begp See function %\begcode next\endcode for the caveats of modifying the table during its traversal. \endp\begp \endp\hrule\subsubsection{\begcode pcall (f, arg1, %·%·%·)\endcode } \begp Calls function \begcode f\endcode with the given arguments in {\em protected mode}. This means that any error inside~\begcode f\endcode is not propagated; instead, \begcode pcall\endcode catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, \begcode pcall\endcode also returns all results from the call, after this first result. In case of any error, \begcode pcall\endcode returns {\bf false} plus the error message. \endp\begp \endp\hrule\subsubsection{\begcode print (%·%·%·)\endcode } Receives any number of arguments, and prints their values to \begcode stdout\endcode , using the %\begcode tostring\endcode function to convert them to strings. \begcode print\endcode is not intended for formatted output, but only as a quick way to show a value, typically for debugging. For formatted output, use %\begcode string.format\endcode . \begp \endp\hrule\subsubsection{\begcode rawequal (v1, v2)\endcode } Checks whether \begcode v1\endcode is equal to \begcode v2\endcode , without invoking any metamethod. Returns a boolean. \begp \endp\hrule\subsubsection{\begcode rawget (table, index)\endcode } Gets the real value of \begcode table[index]\endcode , without invoking any metamethod. \begcode table\endcode must be a table; \begcode index\endcode may be any value. \begp \endp\hrule\subsubsection{\begcode rawset (table, index, value)\endcode } Sets the real value of \begcode table[index]\endcode to \begcode value\endcode , without invoking any metamethod. \begcode table\endcode must be a table, \begcode index\endcode any value different from {\bf nil}, and \begcode value\endcode any Lua value. \begp This function returns \begcode table\endcode . \endp\begp \endp\hrule\subsubsection{\begcode select (index, %·%·%·)\endcode } \begp If \begcode index\endcode is a number, returns all arguments after argument number \begcode index\endcode . Otherwise, \begcode index\endcode must be the string \begcode "#"\endcode , and \begcode select\endcode returns the total number of extra arguments it received. \endp\begp \endp\hrule\subsubsection{\begcode setfenv (f, table)\endcode } \begp Sets the environment to be used by the given function. \begcode f\endcode can be a Lua function or a number that specifies the function at that stack level: Level~1 is the function calling \begcode setfenv\endcode . \begcode setfenv\endcode returns the given function. \endp\begp As a special case, when \begcode f\endcode is 0 \begcode setfenv\endcode changes the environment of the running thread. In this case, \begcode setfenv\endcode returns no values. \endp\begp \endp\hrule\subsubsection{\begcode setmetatable (table, metatable)\endcode } \begp Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from~C.) If \begcode metatable\endcode is {\bf nil}, removes the metatable of the given table. If the original metatable has a \begcode "__metatable"\endcode field, raises an error. \endp\begp This function returns \begcode table\endcode . \endp\begp \endp\hrule\subsubsection{\begcode tonumber (e [, base])\endcode } Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, then \begcode tonumber\endcode returns this number; otherwise, it returns {\bf nil}. \begp An optional argument specifies the base to interpret the numeral. The base may be any integer between 2 and 36, inclusive. In bases above~10, the letter '\begcode A\endcode ' (in either upper or lower case) represents~10, '\begcode B\endcode ' represents~11, and so forth, with '\begcode Z\endcode ' representing 35. In base 10 (the default), the number can have a decimal part, as well as an optional exponent part (see %§2.1). In other bases, only unsigned integers are accepted. \endp\begp \endp\hrule\subsubsection{\begcode tostring (e)\endcode } Receives an argument of any type and converts it to a string in a reasonable format. For complete control of how numbers are converted, use %\begcode string.format\endcode . \begp If the metatable of \begcode e\endcode has a \begcode "__tostring"\endcode field, then \begcode tostring\endcode calls the corresponding value with \begcode e\endcode as argument, and uses the result of the call as its result. \endp\begp \endp\hrule\subsubsection{\begcode type (v)\endcode } Returns the type of its only argument, coded as a string. The possible results of this function are "\begcode nil\endcode " (a string, not the value {\bf nil}), "\begcode number\endcode ", "\begcode string\endcode ", "\begcode boolean\endcode ", "\begcode table\endcode ", "\begcode function\endcode ", "\begcode thread\endcode ", and "\begcode userdata\endcode ". \begp \endp\hrule\subsubsection{\begcode unpack (list [, i [, j]])\endcode } Returns the elements from the given table. This function is equivalent to \begpre return list[i], list[i+1], %·%·%·, list[j] \endpre \begp except that the above code can be written only for a fixed number of elements. By default, \begcode i\endcode is~1 and \begcode j\endcode is the length of the list, as defined by the length operator (see %§2.5.5). \endp\begp \endp\hrule\subsubsection{\begcode _VERSION\endcode } A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is "\begcode Lua 5.1\endcode ". \begp \endp\hrule\subsubsection{\begcode xpcall (f, err)\endcode } \begp This function is similar to %\begcode pcall\endcode , except that you can set a new error handler. \endp\begp \begcode xpcall\endcode calls function \begcode f\endcode in protected mode, using \begcode err\endcode as the error handler. Any error inside \begcode f\endcode is not propagated; instead, \begcode xpcall\endcode catches the error, calls the \begcode err\endcode function with the original error object, and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In this case, \begcode xpcall\endcode also returns all results from the call, after this first result. In case of any error, \begcode xpcall\endcode returns {\bf false} plus the result from \begcode err\endcode . \endp\subsection{5.2 - Coroutine Manipulation} \begp The operations related to coroutines comprise a sub-library of the basic library and come inside the table \begcode coroutine\endcode . See %§2.11 for a general description of coroutines. \endp\begp \endp\hrule\subsubsection{\begcode coroutine.create (f)\endcode } \begp Creates a new coroutine, with body \begcode f\endcode . \begcode f\endcode must be a Lua function. Returns this new coroutine, an object with type \begcode "thread"\endcode . \endp\begp \endp\hrule\subsubsection{\begcode coroutine.resume (co [, val1, %·%·%·])\endcode } \begp Starts or continues the execution of coroutine \begcode co\endcode . The first time you resume a coroutine, it starts running its body. The values \begcode val1\endcode , %·%·%· are passed as the arguments to the body function. If the coroutine has yielded, \begcode resume\endcode restarts it; the values \begcode val1\endcode , %·%·%· are passed as the results from the yield. \endp\begp If the coroutine runs without any errors, \begcode resume\endcode returns {\bf true} plus any values passed to \begcode yield\endcode (if the coroutine yields) or any values returned by the body function (if the coroutine terminates). If there is any error, \begcode resume\endcode returns {\bf false} plus the error message. \endp\begp \endp\hrule\subsubsection{\begcode coroutine.running ()\endcode } \begp Returns the running coroutine, or {\bf nil} when called by the main thread. \endp\begp \endp\hrule\subsubsection{\begcode coroutine.status (co)\endcode } \begp Returns the status of coroutine \begcode co\endcode , as a string: \begcode "running"\endcode , if the coroutine is running (that is, it called \begcode status\endcode ); \begcode "suspended"\endcode , if the coroutine is suspended in a call to \begcode yield\endcode , or if it has not started running yet; \begcode "normal"\endcode if the coroutine is active but not running (that is, it has resumed another coroutine); and \begcode "dead"\endcode if the coroutine has finished its body function, or if it has stopped with an error. \endp\begp \endp\hrule\subsubsection{\begcode coroutine.wrap (f)\endcode } \begp Creates a new coroutine, with body \begcode f\endcode . \begcode f\endcode must be a Lua function. Returns a function that resumes the coroutine each time it is called. Any arguments passed to the function behave as the extra arguments to \begcode resume\endcode . Returns the same values returned by \begcode resume\endcode , except the first boolean. In case of error, propagates the error. \endp\begp \endp\hrule\subsubsection{\begcode coroutine.yield (%·%·%·)\endcode } \begp Suspends the execution of the calling coroutine. The coroutine cannot be running a C~function, a metamethod, or an iterator. Any arguments to \begcode yield\endcode are passed as extra results to \begcode resume\endcode . \endp\subsection{5.3 - Modules} \begp The package library provides basic facilities for loading and building modules in Lua. It exports two of its functions directly in the global environment: %\begcode require\endcode and %\begcode module\endcode . Everything else is exported in a table \begcode package\endcode . \endp\begp \endp\hrule\subsubsection{\begcode module (name [, %·%·%·])\endcode } \begp Creates a module. If there is a table in \begcode package.loaded[name]\endcode , this table is the module. Otherwise, if there is a global table \begcode t\endcode with the given name, this table is the module. Otherwise creates a new table \begcode t\endcode and sets it as the value of the global \begcode name\endcode and the value of \begcode package.loaded[name]\endcode . This function also initializes \begcode t._NAME\endcode with the given name, \begcode t._M\endcode with the module (\begcode t\endcode itself), and \begcode t._PACKAGE\endcode with the package name (the full module name minus last component; see below). Finally, \begcode module\endcode sets \begcode t\endcode as the new environment of the current function and the new value of \begcode package.loaded[name]\endcode , so that %\begcode require\endcode returns \begcode t\endcode . \endp\begp If \begcode name\endcode is a compound name (that is, one with components separated by dots), \begcode module\endcode creates (or reuses, if they already exist) tables for each component. For instance, if \begcode name\endcode is \begcode a.b.c\endcode , then \begcode module\endcode stores the module table in field \begcode c\endcode of field \begcode b\endcode of global \begcode a\endcode . \endp\begp This function can receive optional {\em options} after the module name, where each option is a function to be applied over the module. \endp\begp \endp\hrule\subsubsection{\begcode require (modname)\endcode } \begp Loads the given module. The function starts by looking into the %\begcode package.loaded\endcode table to determine whether \begcode modname\endcode is already loaded. If it is, then \begcode require\endcode returns the value stored at \begcode package.loaded[modname]\endcode . Otherwise, it tries to find a {\em loader} for the module. \endp\begp To find a loader, \begcode require\endcode is guided by the %\begcode package.loaders\endcode array. By changing this array, we can change how \begcode require\endcode looks for a module. The following explanation is based on the default configuration for %\begcode package.loaders\endcode . \endp\begp First \begcode require\endcode queries \begcode package.preload[modname]\endcode . If it has a value, this value (which should be a function) is the loader. Otherwise \begcode require\endcode searches for a Lua loader using the path stored in %\begcode package.path\endcode . If that also fails, it searches for a C~loader using the path stored in %\begcode package.cpath\endcode . If that also fails, it tries an {\em all-in-one} loader (see %\begcode package.loaders\endcode ). \endp\begp Once a loader is found, \begcode require\endcode calls the loader with a single argument, \begcode modname\endcode . If the loader returns any value, \begcode require\endcode assigns the returned value to \begcode package.loaded[modname]\endcode . If the loader returns no value and has not assigned any value to \begcode package.loaded[modname]\endcode , then \begcode require\endcode assigns {\bf true} to this entry. In any case, \begcode require\endcode returns the final value of \begcode package.loaded[modname]\endcode . \endp\begp If there is any error loading or running the module, or if it cannot find any loader for the module, then \begcode require\endcode signals an error. \endp\begp \endp\hrule\subsubsection{\begcode package.cpath\endcode } \begp The path used by %\begcode require\endcode to search for a C~loader. \endp\begp Lua initializes the C~path %\begcode package.cpath\endcode in the same way it initializes the Lua path %\begcode package.path\endcode , using the environment variable \begcode LUA_CPATH\endcode or a default path defined in \begcode luaconf.h\endcode . \endp\begp \endp\hrule\subsubsection{\begcode package.loaded\endcode } \begp A table used by %\begcode require\endcode to control which modules are already loaded. When you require a module \begcode modname\endcode and \begcode package.loaded[modname]\endcode is not false, %\begcode require\endcode simply returns the value stored there. \endp\begp \endp\hrule\subsubsection{\begcode package.loaders\endcode } \begp A table used by %\begcode require\endcode to control how to load modules. \endp\begp Each entry in this table is a {\em searcher function}. When looking for a module, %\begcode require\endcode calls each of these searchers in ascending order, with the module name (the argument given to %\begcode require\endcode ) as its sole parameter. The function can return another function (the module {\em loader}) or a string explaining why it did not find that module (or {\bf nil} if it has nothing to say). Lua initializes this table with four functions. \endp\begp The first searcher simply looks for a loader in the %\begcode package.preload\endcode table. \endp\begp The second searcher looks for a loader as a Lua library, using the path stored at %\begcode package.path\endcode . A path is a sequence of {\em templates} separated by semicolons. For each template, the searcher will change each interrogation mark in the template by \begcode filename\endcode , which is the module name with each dot replaced by a "directory separator" (such as "\begcode /\endcode " in Unix); then it will try to open the resulting file name. So, for instance, if the Lua path is the string \endp\begpre "./?.lua;./?.lc;/usr/local/?/init.lua" \endpre \begp the search for a Lua file for module \begcode foo\endcode will try to open the files \begcode ./foo.lua\endcode , \begcode ./foo.lc\endcode , and \begcode /usr/local/foo/init.lua\endcode , in that order. \endp\begp The third searcher looks for a loader as a C~library, using the path given by the variable %\begcode package.cpath\endcode . For instance, if the C~path is the string \endp\begpre "./?.so;./?.dll;/usr/local/?/init.so" \endpre \begp the searcher for module \begcode foo\endcode will try to open the files \begcode ./foo.so\endcode , \begcode ./foo.dll\endcode , and \begcode /usr/local/foo/init.so\endcode , in that order. Once it finds a C~library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C~function inside the library to be used as the loader. The name of this C~function is the string "\begcode luaopen_\endcode " concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name is \begcode a.v1-b.c\endcode , the function name will be \begcode luaopen_b_c\endcode . \endp\begp The fourth searcher tries an {\em all-in-one loader}. It searches the C~path for a library for the root name of the given module. For instance, when requiring \begcode a.b.c\endcode , it will search for a C~library for \begcode a\endcode . If found, it looks into it for an open function for the submodule; in our example, that would be \begcode luaopen_a_b_c\endcode . With this facility, a package can pack several C~submodules into one single library, with each submodule keeping its original open function. \endp\begp \endp\hrule\subsubsection{\begcode package.loadlib (libname, funcname)\endcode } \begp Dynamically links the host program with the C~library \begcode libname\endcode . Inside this library, looks for a function \begcode funcname\endcode and returns this function as a C~function. (So, \begcode funcname\endcode must follow the protocol (see %\begcode lua_CFunction\endcode )). \endp\begp This is a low-level function. It completely bypasses the package and module system. Unlike %\begcode require\endcode , it does not perform any path searching and does not automatically adds extensions. \begcode libname\endcode must be the complete file name of the C~library, including if necessary a path and extension. \begcode funcname\endcode must be the exact name exported by the C~library (which may depend on the C~compiler and linker used). \endp\begp This function is not supported by ANSI C. As such, it is only available on some platforms (Windows, Linux, Mac OS X, Solaris, BSD, plus other Unix systems that support the \begcode dlfcn\endcode standard). \endp\begp \endp\hrule\subsubsection{\begcode package.path\endcode } \begp The path used by %\begcode require\endcode to search for a Lua loader. \endp\begp At start-up, Lua initializes this variable with the value of the environment variable \begcode LUA_PATH\endcode or with a default path defined in \begcode luaconf.h\endcode , if the environment variable is not defined. Any "\begcode ;;\endcode " in the value of the environment variable is replaced by the default path. \endp\begp \endp\hrule\subsubsection{\begcode package.preload\endcode } \begp A table to store loaders for specific modules (see %\begcode require\endcode ). \endp\begp \endp\hrule\subsubsection{\begcode package.seeall (module)\endcode } \begp Sets a metatable for \begcode module\endcode with its \begcode __index\endcode field referring to the global environment, so that this module inherits values from the global environment. To be used as an option to function %\begcode module\endcode . \endp\subsection{5.4 - String Manipulation} \begp This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position~1 (not at~0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on. \endp\begp The string library provides all its functions inside the table \begcode string\endcode . It also sets a metatable for strings where the \begcode __index\endcode field points to the \begcode string\endcode table. Therefore, you can use the string functions in object-oriented style. For instance, \begcode string.byte(s, i)\endcode can be written as \begcode s:byte(i)\endcode . \endp\begp The string library assumes one-byte character encodings. \endp\begp \endp\hrule\subsubsection{\begcode string.byte (s [, i [, j]])\endcode } Returns the internal numerical codes of the characters \begcode s[i]\endcode , \begcode s[i+1]\endcode , %·%·%·, \begcode s[j]\endcode . The default value for \begcode i\endcode is~1; the default value for \begcode j\endcode is~\begcode i\endcode . \begp Note that numerical codes are not necessarily portable across platforms. \endp\begp \endp\hrule\subsubsection{\begcode string.char (%·%·%·)\endcode } Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument. \begp Note that numerical codes are not necessarily portable across platforms. \endp\begp \endp\hrule\subsubsection{\begcode string.dump (function)\endcode } \begp Returns a string containing a binary representation of the given function, so that a later %\begcode loadstring\endcode on this string returns a copy of the function. \begcode function\endcode must be a Lua function without upvalues. \endp\begp \endp\hrule\subsubsection{\begcode string.find (s, pattern [, init [, plain]])\endcode } Looks for the first match of \begcode pattern\endcode in the string \begcode s\endcode . If it finds a match, then \begcode find\endcode returns the indices of~\begcode s\endcode where this occurrence starts and ends; otherwise, it returns {\bf nil}. A third, optional numerical argument \begcode init\endcode specifies where to start the search; its default value is~1 and can be negative. A value of {\bf true} as a fourth, optional argument \begcode plain\endcode turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in \begcode pattern\endcode being considered "magic". Note that if \begcode plain\endcode is given, then \begcode init\endcode must be given as well. \begp If the pattern has captures, then in a successful match the captured values are also returned, after the two indices. \endp\begp \endp\hrule\subsubsection{\begcode string.format (formatstring, %·%·%·)\endcode } Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the \begcode printf\endcode family of standard C~functions. The only differences are that the options/modifiers \begcode *\endcode , \begcode l\endcode , \begcode L\endcode , \begcode n\endcode , \begcode p\endcode , and \begcode h\endcode are not supported and that there is an extra option, \begcode q\endcode . The \begcode q\endcode option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call \begpre string.format('%q', 'a string with "quotes" and \n new line') \endpre \begp will produce the string: \endp\begpre "a string with \"quotes\" and \ new line" \endpre \begp The options \begcode c\endcode , \begcode d\endcode , \begcode E\endcode , \begcode e\endcode , \begcode f\endcode , \begcode g\endcode , \begcode G\endcode , \begcode i\endcode , \begcode o\endcode , \begcode u\endcode , \begcode X\endcode , and \begcode x\endcode all expect a number as argument, whereas \begcode q\endcode and \begcode s\endcode expect a string. \endp\begp This function does not accept string values containing embedded zeros, except as arguments to the \begcode q\endcode option. \endp\begp \endp\hrule\subsubsection{\begcode string.gmatch (s, pattern)\endcode } Returns an iterator function that, each time it is called, returns the next captures from \begcode pattern\endcode over string \begcode s\endcode . If \begcode pattern\endcode specifies no captures, then the whole match is produced in each call. \begp As an example, the following loop \endp\begpre s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end \endpre \begp will iterate over all the words from string \begcode s\endcode , printing one per line. The next example collects all pairs \begcode key=value\endcode from the given string into a table: \endp\begpre t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end \endpre \begp For this function, a '\begcode ^\endcode ' at the start of a pattern does not work as an anchor, as this would prevent the iteration. \endp\begp \endp\hrule\subsubsection{\begcode string.gsub (s, pattern, repl [, n])\endcode } Returns a copy of \begcode s\endcode in which all (or the first \begcode n\endcode , if given) occurrences of the \begcode pattern\endcode have been replaced by a replacement string specified by \begcode repl\endcode , which can be a string, a table, or a function. \begcode gsub\endcode also returns, as its second value, the total number of matches that occurred. \begp If \begcode repl\endcode is a string, then its value is used for replacement. The character~\begcode %\endcode works as an escape character: any sequence in \begcode repl\endcode of the form \begcode %{\em n}\endcode , with {\em n} between 1 and 9, stands for the value of the {\em n}-th captured substring (see below). The sequence \begcode %0\endcode stands for the whole match. The sequence \begcode %%\endcode stands for a single~\begcode %\endcode . \endp\begp If \begcode repl\endcode is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key. \endp\begp If \begcode repl\endcode is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument. \endp\begp If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is {\bf false} or {\bf nil}, then there is no replacement (that is, the original match is kept in the string). \endp\begp Here are some examples: \endp\begpre 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 loadstring(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz" \endpre \begp \endp\hrule\subsubsection{\begcode string.len (s)\endcode } Receives a string and returns its length. The empty string \begcode ""\endcode has length 0. Embedded zeros are counted, so \begcode "a\000bc\000"\endcode has length 5. \begp \endp\hrule\subsubsection{\begcode string.lower (s)\endcode } Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale. \begp \endp\hrule\subsubsection{\begcode string.match (s, pattern [, init])\endcode } Looks for the first {\em match} of \begcode pattern\endcode in the string \begcode s\endcode . If it finds one, then \begcode match\endcode returns the captures from the pattern; otherwise it returns {\bf nil}. If \begcode pattern\endcode specifies no captures, then the whole match is returned. A third, optional numerical argument \begcode init\endcode specifies where to start the search; its default value is~1 and can be negative. \begp \endp\hrule\subsubsection{\begcode string.rep (s, n)\endcode } Returns a string that is the concatenation of \begcode n\endcode copies of the string \begcode s\endcode . \begp \endp\hrule\subsubsection{\begcode string.reverse (s)\endcode } Returns a string that is the string \begcode s\endcode reversed. \begp \endp\hrule\subsubsection{\begcode string.sub (s, i [, j])\endcode } Returns the substring of \begcode s\endcode that starts at \begcode i\endcode and continues until \begcode j\endcode ; \begcode i\endcode and \begcode j\endcode can be negative. If \begcode j\endcode is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call \begcode string.sub(s,1,j)\endcode returns a prefix of \begcode s\endcode with length \begcode j\endcode , and \begcode string.sub(s, -i)\endcode returns a suffix of \begcode s\endcode with length \begcode i\endcode . \begp \endp\hrule\subsubsection{\begcode string.upper (s)\endcode } Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale. \subsubsection{5.4.1 - Patterns} \subsubsubsection{Character Class:}\begp A {\em character class} is used to represent a set of characters. The following combinations are allowed in describing a character class: \endp
  • {\bf {\em x}:} (where {\em x} is not one of the {\em magic characters} \begcode ^$()%.[]*+-?\endcode ) represents the character {\em x} itself.
  • {\bf \begcode .\endcode :} (a dot) represents all characters.
  • {\bf \begcode %a\endcode :} represents all letters.
  • {\bf \begcode %c\endcode :} represents all control characters.
  • {\bf \begcode %d\endcode :} represents all digits.
  • {\bf \begcode %l\endcode :} represents all lowercase letters.
  • {\bf \begcode %p\endcode :} represents all punctuation characters.
  • {\bf \begcode %s\endcode :} represents all space characters.
  • {\bf \begcode %u\endcode :} represents all uppercase letters.
  • {\bf \begcode %w\endcode :} represents all alphanumeric characters.
  • {\bf \begcode %x\endcode :} represents all hexadecimal digits.
  • {\bf \begcode %z\endcode :} represents the character with representation 0.
  • {\bf \begcode %{\em x}\endcode :} (where {\em x} is any non-alphanumeric character) represents the character {\em x}. This is the standard way to escape the magic characters. Any punctuation character (even the non magic) can be preceded by a '\begcode %\endcode ' when used to represent itself in a pattern.
  • {\bf \begcode [{\em set}]\endcode :} represents the class which is the union of all characters in {\em set}. A range of characters can be specified by separating the end characters of the range with a '\begcode -\endcode '. All classes \begcode %\endcode {\em x} described above can also be used as components in {\em set}. All other characters in {\em set} represent themselves. For example, \begcode [%w_]\endcode (or \begcode [_%w]\endcode ) represents all alphanumeric characters plus the underscore, \begcode [0-7]\endcode represents the octal digits, and \begcode [0-7%l%-]\endcode represents the octal digits plus the lowercase letters plus the '\begcode -\endcode ' character. \begp The interaction between ranges and classes is not defined. Therefore, patterns like \begcode [%a-z]\endcode or \begcode [a-%%]\endcode have no meaning. \endp
  • {\bf \begcode [^{\em set}]\endcode :} represents the complement of {\em set}, where {\em set} is interpreted as above.
\begp For all classes represented by single letters (\begcode %a\endcode , \begcode %c\endcode , etc.), the corresponding uppercase letter represents the complement of the class. For instance, \begcode %S\endcode represents all non-space characters. \endp\begp The definitions of letter, space, and other character groups depend on the current locale. In particular, the class \begcode [a-z]\endcode may not be equivalent to \begcode %l\endcode . \endp\subsubsubsection{Pattern Item:}\begp A {\em pattern item} can be \endp
  • a single character class, which matches any single character in the class;
  • a single character class followed by '\begcode *\endcode ', which matches 0 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '\begcode +\endcode ', which matches 1 or more repetitions of characters in the class. These repetition items will always match the longest possible sequence;
  • a single character class followed by '\begcode -\endcode ', which also matches 0 or more repetitions of characters in the class. Unlike '\begcode *\endcode ', these repetition items will always match the {\em shortest} possible sequence;
  • a single character class followed by '\begcode ?\endcode ', which matches 0 or 1 occurrence of a character in the class;
  • \begcode %{\em n}\endcode , for {\em n} between 1 and 9; such item matches a substring equal to the {\em n}-th captured string (see below);
  • \begcode %b{\em xy}\endcode , where {\em x} and {\em y} are two distinct characters; such item matches strings that start with~{\em x}, end with~{\em y}, and where the {\em x} and {\em y} are {\em balanced}. This means that, if one reads the string from left to right, counting {\em +1} for an {\em x} and {\em -1} for a {\em y}, the ending {\em y} is the first {\em y} where the count reaches 0. For instance, the item \begcode %b()\endcode matches expressions with balanced parentheses.
\subsubsubsection{Pattern:}\begp A {\em pattern} is a sequence of pattern items. A '\begcode ^\endcode ' at the beginning of a pattern anchors the match at the beginning of the subject string. A '\begcode $\endcode ' at the end of a pattern anchors the match at the end of the subject string. At other positions, '\begcode ^\endcode ' and '\begcode $\endcode ' have no special meaning and represent themselves. \endp\subsubsubsection{Captures:}\begp A pattern can contain sub-patterns enclosed in parentheses; they describe {\em captures}. When a match succeeds, the substrings of the subject string that match captures are stored ({\em captured}) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern \begcode "(a*(.)%w(%s*))"\endcode , the part of the string matching \begcode "a*(.)%w(%s*)"\endcode is stored as the first capture (and therefore has number~1); the character matching "\begcode .\endcode " is captured with number~2, and the part matching "\begcode %s*\endcode " has number~3. \endp\begp As a special case, the empty capture \begcode ()\endcode captures the current string position (a number). For instance, if we apply the pattern \begcode "()aa()"\endcode on the string \begcode "flaaap"\endcode , there will be two captures: 3~and~5. \endp\begp A pattern cannot contain embedded zeros. Use \begcode %z\endcode instead. \endp\subsection{5.5 - Table Manipulation}\begp This library provides generic functions for table manipulation. It provides all its functions inside the table \begcode table\endcode . \endp\begp Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator. \endp\begp \endp\hrule\subsubsection{\begcode table.concat (table [, sep [, i [, j]]])\endcode } Given an array where all elements are strings or numbers, returns \begcode table[i]..sep..table[i+1] %·%·%· sep..table[j]\endcode . The default value for \begcode sep\endcode is the empty string, the default for \begcode i\endcode is 1, and the default for \begcode j\endcode is the length of the table. If \begcode i\endcode is greater than \begcode j\endcode , returns the empty string. \begp \endp\hrule\subsubsection{\begcode table.insert (table, [pos,] value)\endcode } \begp Inserts element \begcode value\endcode at position \begcode pos\endcode in \begcode table\endcode , shifting up other elements to open space, if necessary. The default value for \begcode pos\endcode is \begcode n+1\endcode , where \begcode n\endcode is the length of the table (see %§2.5.5), so that a call \begcode table.insert(t,x)\endcode inserts \begcode x\endcode at the end of table \begcode t\endcode . \endp\begp \endp\hrule\subsubsection{\begcode table.maxn (table)\endcode } \begp Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.) \endp\begp \endp\hrule\subsubsection{\begcode table.remove (table [, pos])\endcode } \begp Removes from \begcode table\endcode the element at position \begcode pos\endcode , shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for \begcode pos\endcode is \begcode n\endcode , where \begcode n\endcode is the length of the table, so that a call \begcode table.remove(t)\endcode removes the last element of table \begcode t\endcode . \endp\begp \endp\hrule\subsubsection{\begcode table.sort (table [, comp])\endcode } Sorts table elements in a given order, {\em in-place}, from \begcode table[1]\endcode to \begcode table[n]\endcode , where \begcode n\endcode is the length of the table. If \begcode comp\endcode is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that \begcode not comp(a[i+1],a[i])\endcode will be true after the sort). If \begcode comp\endcode is not given, then the standard Lua operator \begcode <\endcode is used instead. \begp The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort. \endp\subsection{5.6 - Mathematical Functions} \begp This library is an interface to the standard C~math library. It provides all its functions inside the table \begcode math\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.abs (x)\endcode } \begp Returns the absolute value of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.acos (x)\endcode } \begp Returns the arc cosine of \begcode x\endcode (in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.asin (x)\endcode } \begp Returns the arc sine of \begcode x\endcode (in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.atan (x)\endcode } \begp Returns the arc tangent of \begcode x\endcode (in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.atan2 (y, x)\endcode } \begp Returns the arc tangent of \begcode y/x\endcode (in radians), but uses the signs of both parameters to find the quadrant of the result. (It also handles correctly the case of \begcode x\endcode being zero.) \endp\begp \endp\hrule\subsubsection{\begcode math.ceil (x)\endcode } \begp Returns the smallest integer larger than or equal to \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.cos (x)\endcode } \begp Returns the cosine of \begcode x\endcode (assumed to be in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.cosh (x)\endcode } \begp Returns the hyperbolic cosine of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.deg (x)\endcode } \begp Returns the angle \begcode x\endcode (given in radians) in degrees. \endp\begp \endp\hrule\subsubsection{\begcode math.exp (x)\endcode } \begp Returns the value {\em ex}. \endp\begp \endp\hrule\subsubsection{\begcode math.floor (x)\endcode } \begp Returns the largest integer smaller than or equal to \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.fmod (x, y)\endcode } \begp Returns the remainder of the division of \begcode x\endcode by \begcode y\endcode that rounds the quotient towards zero. \endp\begp \endp\hrule\subsubsection{\begcode math.frexp (x)\endcode } \begp Returns \begcode m\endcode and \begcode e\endcode such that {\em x = m2e}, \begcode e\endcode is an integer and the absolute value of \begcode m\endcode is in the range {\em [0.5, 1)} (or zero when \begcode x\endcode is zero). \endp\begp \endp\hrule\subsubsection{\begcode math.huge\endcode } \begp The value \begcode HUGE_VAL\endcode , a value larger than or equal to any other numerical value. \endp\begp \endp\hrule\subsubsection{\begcode math.ldexp (m, e)\endcode } \begp Returns {\em m2e} (\begcode e\endcode should be an integer). \endp\begp \endp\hrule\subsubsection{\begcode math.log (x)\endcode } \begp Returns the natural logarithm of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.log10 (x)\endcode } \begp Returns the base-10 logarithm of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.max (x, %·%·%·)\endcode } \begp Returns the maximum value among its arguments. \endp\begp \endp\hrule\subsubsection{\begcode math.min (x, %·%·%·)\endcode } \begp Returns the minimum value among its arguments. \endp\begp \endp\hrule\subsubsection{\begcode math.modf (x)\endcode } \begp Returns two numbers, the integral part of \begcode x\endcode and the fractional part of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.pi\endcode } \begp The value of {\em pi}. \endp\begp \endp\hrule\subsubsection{\begcode math.pow (x, y)\endcode } \begp Returns {\em xy}. (You can also use the expression \begcode x^y\endcode to compute this value.) \endp\begp \endp\hrule\subsubsection{\begcode math.rad (x)\endcode } \begp Returns the angle \begcode x\endcode (given in degrees) in radians. \endp\begp \endp\hrule\subsubsection{\begcode math.random ([m [, n]])\endcode } \begp This function is an interface to the simple pseudo-random generator function \begcode rand\endcode provided by ANSI~C. (No guarantees can be given for its statistical properties.) \endp\begp When called without arguments, returns a uniform pseudo-random real number in the range {\em [0,1)}. When called with an integer number \begcode m\endcode , \begcode math.random\endcode returns a uniform pseudo-random integer in the range {\em [1, m]}. When called with two integer numbers \begcode m\endcode and \begcode n\endcode , \begcode math.random\endcode returns a uniform pseudo-random integer in the range {\em [m, n]}. \endp\begp \endp\hrule\subsubsection{\begcode math.randomseed (x)\endcode } \begp Sets \begcode x\endcode as the "seed" for the pseudo-random generator: equal seeds produce equal sequences of numbers. \endp\begp \endp\hrule\subsubsection{\begcode math.sin (x)\endcode } \begp Returns the sine of \begcode x\endcode (assumed to be in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.sinh (x)\endcode } \begp Returns the hyperbolic sine of \begcode x\endcode . \endp\begp \endp\hrule\subsubsection{\begcode math.sqrt (x)\endcode } \begp Returns the square root of \begcode x\endcode . (You can also use the expression \begcode x^0.5\endcode to compute this value.) \endp\begp \endp\hrule\subsubsection{\begcode math.tan (x)\endcode } \begp Returns the tangent of \begcode x\endcode (assumed to be in radians). \endp\begp \endp\hrule\subsubsection{\begcode math.tanh (x)\endcode } \begp Returns the hyperbolic tangent of \begcode x\endcode . \endp\subsection{5.7 - Input and Output Facilities} \begp The I/O library provides two different styles for file manipulation. The first one uses implicit file descriptors; that is, there are operations to set a default input file and a default output file, and all input/output operations are over these default files. The second style uses explicit file descriptors. \endp\begp When using implicit file descriptors, all operations are supplied by table \begcode io\endcode . When using explicit file descriptors, the operation %\begcode io.open\endcode returns a file descriptor and then all operations are supplied as methods of the file descriptor. \endp\begp The table \begcode io\endcode also provides three predefined file descriptors with their usual meanings from C: \begcode io.stdin\endcode , \begcode io.stdout\endcode , and \begcode io.stderr\endcode . The I/O library never closes these files. \endp\begp Unless otherwise stated, all I/O functions return {\bf nil} on failure (plus an error message as a second result and a system-dependent error code as a third result) and some value different from {\bf nil} on success. \endp\begp \endp\hrule\subsubsection{\begcode io.close ([file])\endcode } \begp Equivalent to \begcode file:close()\endcode . Without a \begcode file\endcode , closes the default output file. \endp\begp \endp\hrule\subsubsection{\begcode io.flush ()\endcode } \begp Equivalent to \begcode file:flush\endcode over the default output file. \endp\begp \endp\hrule\subsubsection{\begcode io.input ([file])\endcode } \begp When called with a file name, it opens the named file (in text mode), and sets its handle as the default input file. When called with a file handle, it simply sets this file handle as the default input file. When called without parameters, it returns the current default input file. \endp\begp In case of errors this function raises the error, instead of returning an error code. \endp\begp \endp\hrule\subsubsection{\begcode io.lines ([filename])\endcode } \begp Opens the given file name in read mode and returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction \endp\begpre for line in io.lines(filename) do {\em body} end \endpre \begp will iterate over all lines of the file. When the iterator function detects the end of file, it returns {\bf nil} (to finish the loop) and automatically closes the file. \endp\begp The call \begcode io.lines()\endcode (with no file name) is equivalent to \begcode io.input():lines()\endcode ; that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends. \endp\begp \endp\hrule\subsubsection{\begcode io.open (filename [, mode])\endcode } \begp This function opens a file, in the mode specified in the string \begcode mode\endcode . It returns a new file handle, or, in case of errors, {\bf nil} plus an error message. \endp\begp The \begcode mode\endcode string can be any of the following: \endp
  • {\bf "r":} read mode (the default);
  • {\bf "w":} write mode;
  • {\bf "a":} append mode;
  • {\bf "r+":} update mode, all previous data is preserved;
  • {\bf "w+":} update mode, all previous data is erased;
  • {\bf "a+":} append update mode, previous data is preserved, writing is only allowed at the end of file.
\begp The \begcode mode\endcode string can also have a '\begcode b\endcode ' at the end, which is needed in some systems to open the file in binary mode. This string is exactly what is used in the standard~C function \begcode fopen\endcode . \endp\begp \endp\hrule\subsubsection{\begcode io.output ([file])\endcode } \begp Similar to %\begcode io.input\endcode , but operates over the default output file. \endp\begp \endp\hrule\subsubsection{\begcode io.popen (prog [, mode])\endcode } \begp Starts program \begcode prog\endcode in a separated process and returns a file handle that you can use to read data from this program (if \begcode mode\endcode is \begcode "r"\endcode , the default) or to write data to this program (if \begcode mode\endcode is \begcode "w"\endcode ). \endp\begp This function is system dependent and is not available on all platforms. \endp\begp \endp\hrule\subsubsection{\begcode io.read (%·%·%·)\endcode } \begp Equivalent to \begcode io.input():read\endcode . \endp\begp \endp\hrule\subsubsection{\begcode io.tmpfile ()\endcode } \begp Returns a handle for a temporary file. This file is opened in update mode and it is automatically removed when the program ends. \endp\begp \endp\hrule\subsubsection{\begcode io.type (obj)\endcode } \begp Checks whether \begcode obj\endcode is a valid file handle. Returns the string \begcode "file"\endcode if \begcode obj\endcode is an open file handle, \begcode "closed file"\endcode if \begcode obj\endcode is a closed file handle, or {\bf nil} if \begcode obj\endcode is not a file handle. \endp\begp \endp\hrule\subsubsection{\begcode io.write (%·%·%·)\endcode } \begp Equivalent to \begcode io.output():write\endcode . \endp\begp \endp\hrule\subsubsection{\begcode file:close ()\endcode } \begp Closes \begcode file\endcode . Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen. \endp\begp \endp\hrule\subsubsection{\begcode file:flush ()\endcode } \begp Saves any written data to \begcode file\endcode . \endp\begp \endp\hrule\subsubsection{\begcode file:lines ()\endcode } \begp Returns an iterator function that, each time it is called, returns a new line from the file. Therefore, the construction \endp\begpre for line in file:lines() do {\em body} end \endpre \begp will iterate over all lines of the file. (Unlike %\begcode io.lines\endcode , this function does not close the file when the loop ends.) \endp\begp \endp\hrule\subsubsection{\begcode file:read (%·%·%·)\endcode } \begp Reads the file \begcode file\endcode , according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or {\bf nil} if it cannot read data with the specified format. When called without formats, it uses a default format that reads the entire next line (see below). \endp\begp The available formats are \endp
  • {\bf "*n":} reads a number; this is the only format that returns a number instead of a string.
  • {\bf "*a":} reads the whole file, starting at the current position. On end of file, it returns the empty string.
  • {\bf "*l":} reads the next line (skipping the end of line), returning {\bf nil} on end of file. This is the default format.
  • {\bf {\em number}:} reads a string with up to this number of characters, returning {\bf nil} on end of file. If number is zero, it reads nothing and returns an empty string, or {\bf nil} on end of file.
\begp \endp\hrule\subsubsection{\begcode file:seek ([whence] [, offset])\endcode } \begp Sets and gets the file position, measured from the beginning of the file, to the position given by \begcode offset\endcode plus a base specified by the string \begcode whence\endcode , as follows: \endp
  • {\bf "set":} base is position 0 (beginning of the file);
  • {\bf "cur":} base is current position;
  • {\bf "end":} base is end of file;
\begp In case of success, function \begcode seek\endcode returns the final file position, measured in bytes from the beginning of the file. If this function fails, it returns {\bf nil}, plus a string describing the error. \endp\begp The default value for \begcode whence\endcode is \begcode "cur"\endcode , and for \begcode offset\endcode is 0. Therefore, the call \begcode file:seek()\endcode returns the current file position, without changing it; the call \begcode file:seek("set")\endcode sets the position to the beginning of the file (and returns 0); and the call \begcode file:seek("end")\endcode sets the position to the end of the file, and returns its size. \endp\begp \endp\hrule\subsubsection{\begcode file:setvbuf (mode [, size])\endcode } \begp Sets the buffering mode for an output file. There are three available modes: \endp
  • {\bf "no":} no buffering; the result of any output operation appears immediately.
  • {\bf "full":} full buffering; output operation is performed only when the buffer is full (or when you explicitly \begcode flush\endcode the file (see %\begcode io.flush\endcode )).
  • {\bf "line":} line buffering; output is buffered until a newline is output or there is any input from some special files (such as a terminal device).
\begp For the last two cases, \begcode size\endcode specifies the size of the buffer, in bytes. The default is an appropriate size. \endp\begp \endp\hrule\subsubsection{\begcode file:write (%·%·%·)\endcode } \begp Writes the value of each of its arguments to the \begcode file\endcode . The arguments must be strings or numbers. To write other values, use %\begcode tostring\endcode or %\begcode string.format\endcode before \begcode write\endcode . \endp\subsection{5.8 - Operating System Facilities} \begp This library is implemented through table \begcode os\endcode . \endp\begp \endp\hrule\subsubsection{\begcode os.clock ()\endcode } \begp Returns an approximation of the amount in seconds of CPU time used by the program. \endp\begp \endp\hrule\subsubsection{\begcode os.date ([format [, time]])\endcode } \begp Returns a string or a table containing date and time, formatted according to the given string \begcode format\endcode . \endp\begp If the \begcode time\endcode argument is present, this is the time to be formatted (see the %\begcode os.time\endcode function for a description of this value). Otherwise, \begcode date\endcode formats the current time. \endp\begp If \begcode format\endcode starts with '\begcode !\endcode ', then the date is formatted in Coordinated Universal Time. After this optional character, if \begcode format\endcode is the string "\begcode *t\endcode ", then \begcode date\endcode returns a table with the following fields: \begcode year\endcode (four digits), \begcode month\endcode (1--12), \begcode day\endcode (1--31), \begcode hour\endcode (0--23), \begcode min\endcode (0--59), \begcode sec\endcode (0--61), \begcode wday\endcode (weekday, Sunday is~1), \begcode yday\endcode (day of the year), and \begcode isdst\endcode (daylight saving flag, a boolean). \endp\begp If \begcode format\endcode is not "\begcode *t\endcode ", then \begcode date\endcode returns the date as a string, formatted according to the same rules as the C~function \begcode strftime\endcode . \endp\begp When called without arguments, \begcode date\endcode returns a reasonable date and time representation that depends on the host system and on the current locale (that is, \begcode os.date()\endcode is equivalent to \begcode os.date("%c")\endcode ). \endp\begp \endp\hrule\subsubsection{\begcode os.difftime (t2, t1)\endcode } \begp Returns the number of seconds from time \begcode t1\endcode to time \begcode t2\endcode . In POSIX, Windows, and some other systems, this value is exactly \begcode t2\endcode {\em -}\begcode t1\endcode . \endp\begp \endp\hrule\subsubsection{\begcode os.execute ([command])\endcode } \begp This function is equivalent to the C~function \begcode system\endcode . It passes \begcode command\endcode to be executed by an operating system shell. It returns a status code, which is system-dependent. If \begcode command\endcode is absent, then it returns nonzero if a shell is available and zero otherwise. \endp\begp \endp\hrule\subsubsection{\begcode os.exit ([code])\endcode } \begp Calls the C~function \begcode exit\endcode , with an optional \begcode code\endcode , to terminate the host program. The default value for \begcode code\endcode is the success code. \endp\begp \endp\hrule\subsubsection{\begcode os.getenv (varname)\endcode } \begp Returns the value of the process environment variable \begcode varname\endcode , or {\bf nil} if the variable is not defined. \endp\begp \endp\hrule\subsubsection{\begcode os.remove (filename)\endcode } \begp Deletes the file or directory with the given name. Directories must be empty to be removed. If this function fails, it returns {\bf nil}, plus a string describing the error. \endp\begp \endp\hrule\subsubsection{\begcode os.rename (oldname, newname)\endcode } \begp Renames file or directory named \begcode oldname\endcode to \begcode newname\endcode . If this function fails, it returns {\bf nil}, plus a string describing the error. \endp\begp \endp\hrule\subsubsection{\begcode os.setlocale (locale [, category])\endcode } \begp Sets the current locale of the program. \begcode locale\endcode is a string specifying a locale; \begcode category\endcode is an optional string describing which category to change: \begcode "all"\endcode , \begcode "collate"\endcode , \begcode "ctype"\endcode , \begcode "monetary"\endcode , \begcode "numeric"\endcode , or \begcode "time"\endcode ; the default category is \begcode "all"\endcode . The function returns the name of the new locale, or {\bf nil} if the request cannot be honored. \endp\begp If \begcode locale\endcode is the empty string, the current locale is set to an implementation-defined native locale. If \begcode locale\endcode is the string "\begcode C\endcode ", the current locale is set to the standard C locale. \endp\begp When called with {\bf nil} as the first argument, this function only returns the name of the current locale for the given category. \endp\begp \endp\hrule\subsubsection{\begcode os.time ([table])\endcode } \begp Returns the current time when called without arguments, or a time representing the date and time specified by the given table. This table must have fields \begcode year\endcode , \begcode month\endcode , and \begcode day\endcode , and may have fields \begcode hour\endcode , \begcode min\endcode , \begcode sec\endcode , and \begcode isdst\endcode (for a description of these fields, see the %\begcode os.date\endcode function). \endp\begp The returned value is a number, whose meaning depends on your system. In POSIX, Windows, and some other systems, this number counts the number of seconds since some given start time (the "epoch"). In other systems, the meaning is not specified, and the number returned by \begcode time\endcode can be used only as an argument to \begcode date\endcode and \begcode difftime\endcode . \endp\begp \endp\hrule\subsubsection{\begcode os.tmpname ()\endcode } \begp Returns a string with a file name that can be used for a temporary file. The file must be explicitly opened before its use and explicitly removed when no longer needed. \endp\begp On some systems (POSIX), this function also creates a file with that name, to avoid security risks. (Someone else might create the file with wrong permissions in the time between getting the name and creating the file.) You still have to open the file to use it and to remove it (even if you do not use it). \endp\begp When possible, you may prefer to use %\begcode io.tmpfile\endcode , which automatically removes the file when the program ends. \endp\subsection{5.9 - The Debug Library} \begp This library provides the functionality of the debug interface to Lua programs. You should exert care when using this library. The functions provided here should be used exclusively for debugging and similar tasks, such as profiling. Please resist the temptation to use them as a usual programming tool: they can be very slow. Moreover, several of these functions violate some assumptions about Lua code (e.g., that variables local to a function cannot be accessed from outside or that userdata metatables cannot be changed by Lua code) and therefore can compromise otherwise secure code. \endp\begp All functions in this library are provided inside the \begcode debug\endcode table. All functions that operate over a thread have an optional first argument which is the thread to operate over. The default is always the current thread. \endp\begp \endp\hrule\subsubsection{\begcode debug.debug ()\endcode } \begp Enters an interactive mode with the user, running each string that the user enters. Using simple commands and other debug facilities, the user can inspect global and local variables, change their values, evaluate expressions, and so on. A line containing only the word \begcode cont\endcode finishes this function, so that the caller continues its execution. \endp\begp Note that commands for \begcode debug.debug\endcode are not lexically nested within any function, and so have no direct access to local variables. \endp\begp \endp\hrule\subsubsection{\begcode debug.getfenv (o)\endcode } Returns the environment of object \begcode o\endcode . \begp \endp\hrule\subsubsection{\begcode debug.gethook ([thread])\endcode } \begp Returns the current hook settings of the thread, as three values: the current hook function, the current hook mask, and the current hook count (as set by the %\begcode debug.sethook\endcode function). \endp\begp \endp\hrule\subsubsection{\begcode debug.getinfo ([thread,] function [, what])\endcode } \begp Returns a table with information about a function. You can give the function directly, or you can give a number as the value of \begcode function\endcode , which means the function running at level \begcode function\endcode of the call stack of the given thread: level~0 is the current function (\begcode getinfo\endcode itself); level~1 is the function that called \begcode getinfo\endcode ; and so on. If \begcode function\endcode is a number larger than the number of active functions, then \begcode getinfo\endcode returns {\bf nil}. \endp\begp The returned table can contain all the fields returned by %\begcode lua_getinfo\endcode , with the string \begcode what\endcode describing which fields to fill in. The default for \begcode what\endcode is to get all information available, except the table of valid lines. If present, the option '\begcode f\endcode ' adds a field named \begcode func\endcode with the function itself. If present, the option '\begcode L\endcode ' adds a field named \begcode activelines\endcode with the table of valid lines. \endp\begp For instance, the expression \begcode debug.getinfo(1,"n").name\endcode returns a table with a name for the current function, if a reasonable name can be found, and the expression \begcode debug.getinfo(print)\endcode returns a table with all available information about the %\begcode print\endcode function. \endp\begp \endp\hrule\subsubsection{\begcode debug.getlocal ([thread,] level, local)\endcode } \begp This function returns the name and the value of the local variable with index \begcode local\endcode of the function at level \begcode level\endcode of the stack. (The first parameter or local variable has index~1, and so on, until the last active local variable.) The function returns {\bf nil} if there is no local variable with the given index, and raises an error when called with a \begcode level\endcode out of range. (You can call %\begcode debug.getinfo\endcode to check whether the level is valid.) \endp\begp Variable names starting with '\begcode (\endcode ' (open parentheses) represent internal variables (loop control variables, temporaries, and C~function locals). \endp\begp \endp\hrule\subsubsection{\begcode debug.getmetatable (object)\endcode } \begp Returns the metatable of the given \begcode object\endcode or {\bf nil} if it does not have a metatable. \endp\begp \endp\hrule\subsubsection{\begcode debug.getregistry ()\endcode } \begp Returns the registry table (see %§3.5). \endp\begp \endp\hrule\subsubsection{\begcode debug.getupvalue (func, up)\endcode } \begp This function returns the name and the value of the upvalue with index \begcode up\endcode of the function \begcode func\endcode . The function returns {\bf nil} if there is no upvalue with the given index. \endp\begp \endp\hrule\subsubsection{\begcode debug.setfenv (object, table)\endcode } \begp Sets the environment of the given \begcode object\endcode to the given \begcode table\endcode . Returns \begcode object\endcode . \endp\begp \endp\hrule\subsubsection{\begcode debug.sethook ([thread,] hook, mask [, count])\endcode } \begp Sets the given function as a hook. The string \begcode mask\endcode and the number \begcode count\endcode describe when the hook will be called. The string mask may have the following characters, with the given meaning: \endp
  • {\bf \begcode "c"\endcode :} the hook is called every time Lua calls a function;
  • {\bf \begcode "r"\endcode :} the hook is called every time Lua returns from a function;
  • {\bf \begcode "l"\endcode :} the hook is called every time Lua enters a new line of code.
\begp With a \begcode count\endcode different from zero, the hook is called after every \begcode count\endcode instructions. \endp\begp When called without arguments, %\begcode debug.sethook\endcode turns off the hook. \endp\begp When the hook is called, its first parameter is a string describing the event that has triggered its call: \begcode "call"\endcode , \begcode "return"\endcode (or \begcode "tail return"\endcode , when simulating a return from a tail call), \begcode "line"\endcode , and \begcode "count"\endcode . For line events, the hook also gets the new line number as its second parameter. Inside a hook, you can call \begcode getinfo\endcode with level~2 to get more information about the running function (level~0 is the \begcode getinfo\endcode function, and level~1 is the hook function), unless the event is \begcode "tail return"\endcode . In this case, Lua is only simulating the return, and a call to \begcode getinfo\endcode will return invalid data. \endp\begp \endp\hrule\subsubsection{\begcode debug.setlocal ([thread,] level, local, value)\endcode } \begp This function assigns the value \begcode value\endcode to the local variable with index \begcode local\endcode of the function at level \begcode level\endcode of the stack. The function returns {\bf nil} if there is no local variable with the given index, and raises an error when called with a \begcode level\endcode out of range. (You can call \begcode getinfo\endcode to check whether the level is valid.) Otherwise, it returns the name of the local variable. \endp\begp \endp\hrule\subsubsection{\begcode debug.setmetatable (object, table)\endcode } \begp Sets the metatable for the given \begcode object\endcode to the given \begcode table\endcode (which can be {\bf nil}). \endp\begp \endp\hrule\subsubsection{\begcode debug.setupvalue (func, up, value)\endcode } \begp This function assigns the value \begcode value\endcode to the upvalue with index \begcode up\endcode of the function \begcode func\endcode . The function returns {\bf nil} if there is no upvalue with the given index. Otherwise, it returns the name of the upvalue. \endp\begp \endp\hrule \subsubsection{\begcode debug.traceback ([thread,] [message] [, level])\endcode } \begp Returns a string with a traceback of the call stack. An optional \begcode message\endcode string is appended at the beginning of the traceback. An optional \begcode level\endcode number tells at which level to start the traceback (default is 1, the function calling \begcode traceback\endcode ). \endp\section{6 - Lua Stand-alone} \begp Although Lua has been designed as an extension language, to be embedded in a host C~program, it is also frequently used as a stand-alone language. An interpreter for Lua as a stand-alone language, called simply \begcode lua\endcode , is provided with the standard distribution. The stand-alone interpreter includes all standard libraries, including the debug library. Its usage is: \endp\begpre lua [options] [script [args]] \endpre \begp The options are: \endp
  • {\bf \begcode -e {\em stat}\endcode :} executes string {\em stat};
  • {\bf \begcode -l {\em mod}\endcode :} "requires" {\em mod};
  • {\bf \begcode -i\endcode :} enters interactive mode after running {\em script};
  • {\bf \begcode -v\endcode :} prints version information;
  • {\bf \begcode --\endcode :} stops handling options;
  • {\bf \begcode -\endcode :} executes \begcode stdin\endcode as a file and stops handling options.
\begp After handling its options, \begcode lua\endcode runs the given {\em script}, passing to it the given {\em args} as string arguments. When called without arguments, \begcode lua\endcode behaves as \begcode lua -v -i\endcode when the standard input (\begcode stdin\endcode ) is a terminal, and as \begcode lua -\endcode otherwise. \endp\begp Before running any argument, the interpreter checks for an environment variable \begcode LUA_INIT\endcode . If its format is \begcode @{\em filename}\endcode , then \begcode lua\endcode executes the file. Otherwise, \begcode lua\endcode executes the string itself. \endp\begp All options are handled in order, except \begcode -i\endcode . For instance, an invocation like \endp\begpre $ lua -e'a=1' -e 'print(a)' script.lua \endpre \begp will first set \begcode a\endcode to 1, then print the value of \begcode a\endcode (which is '\begcode 1\endcode '), and finally run the file \begcode script.lua\endcode with no arguments. (Here \begcode $\endcode is the shell prompt. Your prompt may be different.) \endp\begp Before starting to run the script, \begcode lua\endcode collects all arguments in the command line in a global table called \begcode arg\endcode . The script name is stored at index 0, the first argument after the script name goes to index 1, and so on. Any arguments before the script name (that is, the interpreter name plus the options) go to negative indices. For instance, in the call \endp\begpre $ lua -la b.lua t1 t2 \endpre \begp the interpreter first runs the file \begcode a.lua\endcode , then creates a table \endp\begpre arg = { [-2] = "lua", [-1] = "-la", [0] = "b.lua", [1] = "t1", [2] = "t2" } \endpre \begp and finally runs the file \begcode b.lua\endcode . The script is called with \begcode arg[1]\endcode , \begcode arg[2]\endcode , %·%·%· as arguments; it can also access these arguments with the vararg expression '\begcode ...\endcode '. \endp\begp In interactive mode, if you write an incomplete statement, the interpreter waits for its completion by issuing a different prompt. \endp\begp If the global variable \begcode _PROMPT\endcode contains a string, then its value is used as the prompt. Similarly, if the global variable \begcode _PROMPT2\endcode contains a string, its value is used as the secondary prompt (issued during incomplete statements). Therefore, both prompts can be changed directly on the command line or in any Lua programs by assigning to \begcode _PROMPT\endcode . See the next example: \endp\begpre $ lua -e"_PROMPT='myprompt> '" -i \endpre \begp (The outer pair of quotes is for the shell, the inner pair is for Lua.) Note the use of \begcode -i\endcode to enter interactive mode; otherwise, the program would just end silently right after the assignment to \begcode _PROMPT\endcode . \endp\begp To allow the use of Lua as a script interpreter in Unix systems, the stand-alone interpreter skips the first line of a chunk if it starts with \begcode #\endcode . Therefore, Lua scripts can be made into executable programs by using \begcode chmod +x\endcode and the~\begcode #!\endcode form, as in \endp\begpre #!/usr/local/bin/lua \endpre \begp (Of course, the location of the Lua interpreter may be different in your machine. If \begcode lua\endcode is in your \begcode PATH\endcode , then \endp\begpre #!/usr/bin/env lua \endpre \begp is a more portable solution.) \endp\section{7 - Incompatibilities with the Previous Version} \begp Here we list the incompatibilities that you may find when moving a program from Lua~5.0 to Lua~5.1. You can avoid most of the incompatibilities compiling Lua with appropriate options (see file \begcode luaconf.h\endcode ). However, all these compatibility options will be removed in the next version of Lua. \endp\subsection{7.1 - Changes in the Language}
  • The vararg system changed from the pseudo-argument \begcode arg\endcode with a table with the extra arguments to the vararg expression. (See compile-time option \begcode LUA_COMPAT_VARARG\endcode in \begcode luaconf.h\endcode .)
  • There was a subtle change in the scope of the implicit variables of the {\bf for} statement and for the {\bf repeat} statement.
  • The long string/long comment syntax (\begcode [[{\em string}]]\endcode ) does not allow nesting. You can use the new syntax (\begcode [=[{\em string}]=]\endcode ) in these cases. (See compile-time option \begcode LUA_COMPAT_LSTR\endcode in \begcode luaconf.h\endcode .)
\subsection{7.2 - Changes in the Libraries}
  • Function \begcode string.gfind\endcode was renamed %\begcode string.gmatch\endcode . (See compile-time option \begcode LUA_COMPAT_GFIND\endcode in \begcode luaconf.h\endcode .)
  • When %\begcode string.gsub\endcode is called with a function as its third argument, whenever this function returns {\bf nil} or {\bf false} the replacement string is the whole match, instead of the empty string.
  • Function \begcode table.setn\endcode was deprecated. Function \begcode table.getn\endcode corresponds to the new length operator (\begcode #\endcode ); use the operator instead of the function. (See compile-time option \begcode LUA_COMPAT_GETN\endcode in \begcode luaconf.h\endcode .)
  • Function \begcode loadlib\endcode was renamed %\begcode package.loadlib\endcode . (See compile-time option \begcode LUA_COMPAT_LOADLIB\endcode in \begcode luaconf.h\endcode .)
  • Function \begcode math.mod\endcode was renamed %\begcode math.fmod\endcode . (See compile-time option \begcode LUA_COMPAT_MOD\endcode in \begcode luaconf.h\endcode .)
  • Functions \begcode table.foreach\endcode and \begcode table.foreachi\endcode are deprecated. You can use a for loop with \begcode pairs\endcode or \begcode ipairs\endcode instead.
  • There were substantial changes in function %\begcode require\endcode due to the new module system. However, the new behavior is mostly compatible with the old, but \begcode require\endcode gets the path from %\begcode package.path\endcode instead of from \begcode LUA_PATH\endcode .
  • Function %\begcode collectgarbage\endcode has different arguments. Function \begcode gcinfo\endcode is deprecated; use \begcode collectgarbage("count")\endcode instead.
\subsection{7.3 - Changes in the API}
  • The \begcode luaopen_*\endcode functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function.
  • Function \begcode lua_open\endcode was replaced by %\begcode lua_newstate\endcode to allow the user to set a memory-allocation function. You can use %\begcode luaL_newstate\endcode from the standard library to create a state with a standard allocation function (based on \begcode realloc\endcode ).
  • Functions \begcode luaL_getn\endcode and \begcode luaL_setn\endcode (from the auxiliary library) are deprecated. Use %\begcode lua_objlen\endcode instead of \begcode luaL_getn\endcode and nothing instead of \begcode luaL_setn\endcode .
  • Function \begcode luaL_openlib\endcode was replaced by %\begcode luaL_register\endcode .
  • Function \begcode luaL_checkudata\endcode now throws an error when the given value is not a userdata of the expected type. (In Lua~5.0 it returned \begcode NULL\endcode.)
\begp \endp\section{8 - The Complete Syntax of Lua} \begp Here is the complete syntax of Lua in extended BNF. (It does not describe operator precedences.) \endp\begpre chunk ::= {stat [`{\bf ;} ]} [laststat [`{\bf ;} ]] block ::= chunk stat ::= varlist `{\bf =} explist | functioncall | {\bf do} block {\bf end} | {\bf while} exp {\bf do} block {\bf end} | {\bf repeat} block {\bf until} exp | {\bf if} exp {\bf then} block {{\bf elseif} exp {\bf then} block} [{\bf else} block] {\bf end} | {\bf for} Name `{\bf =} exp `{\bf ,} exp [`{\bf ,} exp] {\bf do} block {\bf end} | {\bf for} namelist {\bf in} explist {\bf do} block {\bf end} | {\bf function} funcname funcbody | {\bf local} {\bf function} Name funcbody | {\bf local} namelist [`{\bf =} explist] laststat ::= {\bf return} [explist] | {\bf break} funcname ::= Name {`{\bf .} Name} [`{\bf :} Name] varlist ::= var {`{\bf ,} var} var ::= Name | prefixexp `{\bf [} exp `{\bf ]} | prefixexp `{\bf .} Name namelist ::= Name {`{\bf ,} Name} explist ::= {exp `{\bf ,} } exp exp ::= {\bf nil} | {\bf false} | {\bf true} | Number | String | `{\bf ...} | function | prefixexp | tableconstructor | exp binop exp | unop exp prefixexp ::= var | functioncall | `{\bf (} exp `{\bf )} functioncall ::= prefixexp args | prefixexp `{\bf :} Name args args ::= `{\bf (} [explist] `{\bf )} | tableconstructor | String function ::= {\bf function} funcbody funcbody ::= `{\bf (} [parlist] `{\bf )} block {\bf end} parlist ::= namelist [`{\bf ,} `{\bf ...} ] | `{\bf ...} tableconstructor ::= `{\bf {} [fieldlist] `{\bf }} fieldlist ::= field {fieldsep field} [fieldsep] field ::= `{\bf [} exp `{\bf ]} `{\bf =} exp | Name `{\bf =} exp | exp fieldsep ::= `{\bf ,} | `{\bf ;} binop ::= `{\bf +} | `{\bf -} | `{\bf *} | `{\bf /} | `{\bf ^} | `{\bf %} | `{\bf ..} | `{\bf <} | `{\bf <=} | `{\bf >} | `{\bf >=} | `{\bf ==} | `{\bf ~=} | {\bf and} | {\bf or} unop ::= `{\bf -} | {\bf not} | `{\bf #} \endpre \begp \endp\hrule \begsmall Last update: Wed Jul 28 09:52:30 BRT 2010 \endsmall