Lua 5.1 Reference Manual
Lua 5.1 Reference Manual
1 Reference Manual
Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes March 26, 2 !
1 - Introduction
Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight scripting language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of !"I C and C##$. %eing an extension language, Lua has no notion of a &main' program( it only wor)s embedded in a host client, called the embedding program or simply the host. *his host program can invo)e functions to execute a piece of Lua code, can write and read Lua variables, and can register C functions to be called by Lua code. *hrough the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customi+ed programming languages sharing a syntactical framewor). *he Lua distribution includes a sample host program called lua, which uses the Lua library to offer a complete, stand-alone Lua interpreter. Lua is free software, and is provided as usual with no guarantees, as stated in its license. *he implementation described in this manual is available at Lua,s official web site, www.lua.org. Li)e any other reference manual, this document is dry in places. -or a discussion of the decisions behind the design of Lua, see the technical papers available at Lua,s web site. -or a detailed introduction to programming in Lua, see .oberto,s boo), Programming in Lua (Second Edition).
2 - The Language
*his section describes the lexis, the syntax, and the semantics of Lua. In other words, this section describes which to)ens are valid, how they can be combined, and what their combinations mean. *he language constructs will be explained using the usual extended %!- notation, in which /a0 means 1 or more as, and 2a3 means an optional a. !on-terminals are shown li)e non-terminal, )eywords are shown li)e "#ord, and other terminal symbols are shown li)e 4$5. *he complete syntax of Lua can be found at the end of this manual.
while
Lua is a case-sensitive language( and is a reserved word, but And and AND are two different, valid names. s a convention, names starting with an underscore followed by uppercase letters (such as _VERSION$ are reserved for internal global variables used by Lua. *he following strings denote other to)ens(
-6-
+ == ( %
~= &
* <= ! '
/ >= " (
% < # ((
^ > $ (((
# =
Literal strings can be delimited by matching single or double 7uotes, and can contain the following C-li)e escape se7uences( ,\a, (bell$, ,\b, (bac)space$, ,\f, (form feed$, ,\n, (newline$, ,\r, (carriage return$, ,\t, (hori+ontal tab$, ,\v, (vertical tab$, ,\\, (bac)slash$, ,\", (7uotation mar) 2double 7uote3$, and ,\', (apostrophe 2single 7uote3$. 8oreover, a bac)slash followed by a real newline results in a newline in the string. character in a string may also be specified by its numerical value using the escape se7uence \ddd, where ddd is a se7uence of up to three decimal digits. (!ote that if a numerical escape is to be followed by a digit, it must be expressed using exactly three digits.$ "trings in Lua may contain any 9-bit value, including embedded +eros, which can be specified as ,\0,. *o put a double (single$ 7uote, a newline, a bac)slash, or an embedded +ero inside a literal string enclosed by double (single$ 7uotes you must use an escape se7uence. ny other character may be directly inserted into the literal. ("ome control characters may cause problems for the file system, but Lua has no problem with them.$ Literal strings can also be defined using a long format enclosed by long brackets. :e define an opening long bracket of level n as an opening s7uare brac)et followed by n e7ual signs followed by another opening s7uare brac)et. "o, an opening long brac)et of level 1 is written as [[, an opening long brac)et of level 6 is written as [=[, and so on. closing long bracket is defined similarly; for instance, a closing long brac)et of level < is written as ]====]. long string starts with an opening long brac)et of any level and ends at the first closing long brac)et of the same level. Literals in this brac)eted form may run for several lines, do not interpret any escape se7uences, and ignore long brac)ets of any other level. *hey may contain anything except a closing brac)et of the proper level. -or convenience, when the opening long brac)et is immediately followed by a newline, the newline is not included in the string. s an example, in a system using "CII (in which ,a, is coded as =>, newline is coded as 61, and , , is coded as <=$, the five literals below denote the same string(
a = )alo*n+,-.) a = .alo*n+,-*.. a = )*/0lo*+1*12/,-.) a = ##alo +,-.$$ a = #==# alo +,-.$==$
numerical constant may be written with an optional decimal part and an optional decimal exponent. Lua also accepts integer hexadecimal constants, by prefixing them with 0!. ?xamples of valid numerical constants are
-(1 -(+2+3 -+2(+3e-, 1(-+2+34+ 15ff 1563
comment starts with a double hyphen (""$ anywhere outside a string. If the text immediately after "" is not an opening long brac)et, the comment is a short comment, which runs until the end of the line. @therwise, it is a long comment, which runs until the corresponding closing long brac)et. Long comments are fre7uently used to disable code temporarily.
integers; see file lua#onf.$.$ String represents arrays of characters. Lua is 9-bit clean( strings may contain any 9-bit character, including embedded +eros (,\0,$ (see BA.6$. Lua can call (and manipulate$ functions written in Lua and functions written in C (see BA.C.9$. *he type userdata is provided to allow arbitrary C data to be stored in Lua variables. *his type corresponds to a bloc) of raw memory and has no pre-defined operations in Lua, except assignment and identity test. Dowever, by using metatables, the programmer can define operations for userdata values (see BA.9$. Eserdata values cannot be created or modified in Lua, only through the C FI. *his guarantees the integrity of data owned by the host program. *he type thread represents independent threads of execution and it is used to implement coroutines (see BA.66$. Go not confuse Lua threads with operating-system threads. Lua supports coroutines on all systems, even those that do not support threads. *he type table implements associative arrays, that is, arrays that can be indexed not only with numbers, but with any value (except nil$. *ables can be heterogeneous; that is, they can contain values of all types (except nil$. *ables are the sole data structuring mechanism in Lua; they may be used to represent ordinary arrays, symbol tables, sets, records, graphs, trees, etc. *o represent records, Lua uses the field name as an index. *he language supports this representation by providing a.na%& as syntactic sugar for a["na%&"]. *here are several convenient ways to create tables in Lua (see BA.C.>$. Li)e indices, the value of a table field can be of any type (except nil$. In particular, because functions are firstclass values, table fields may contain functions. *hus tables may also carry methods (see BA.C.=$. *ables, functions, threads, and (full$ userdata values are ob"ects( variables do not actually contain these values, only references to them. ssignment, parameter passing, and function returns always manipulate references to such values; these operations do not imply any )ind of copy. *he library function t'(& returns a string describing the type of a given value. 2.2.1 - Coercion Lua provides automatic conversion between string and number values at run time. ny 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. -or complete control over how numbers are converted to strings, use the for%at function from the string library (see )tr*ng.for%at$.
2.! - Varia"les
Hariables are places that store values. *here are three )inds of variables in Lua( global variables, local variables, and table fields. single name can denote a global variable or a local variable (or a function,s formal parameter, which is a particular )ind of local variable$(
7ar &&= 8a9e
!ame denotes identifiers, as defined in BA.6. ny variable is assumed to be global unless explicitly declared as a local (see BA.<.>$. Local variables are le#ically scoped( local variables can be freely accessed by functions defined inside their scope (see BA.I$. %efore the first assignment to a variable, its value is nil. "7uare brac)ets are used to index a table(
7ar &&= prefi5e5p :[; e5p :];
*he meaning of accesses to global variables and table fields can be changed via metatables. n access to an indexed variable t[*] is e7uivalent to a call g&ttabl&_&v&nt+t,*-. ("ee BA.9 for a complete description of the g&ttabl&_&v&nt function. *his function is not defined or callable in Lua. :e use it here only for explanatory purposes.$ *he syntax var.Na%& is just syntactic sugar for var["Na%&"](
-J-
ll global variables live as fields in ordinary Lua tables, called environment tables or simply environments (see BA.=$. ?ach function has its own reference to an environment, so that all global variables in this function will refer to this environment table. :hen a function is created, it inherits the environment from the function that created it. *o get the environment table of a Lua function, you call g&tf&nv. *o replace it, you call )&tf&nv. (Kou can only manipulate the environment of C functions through the debug library; (see BC.=$.$ n access to a global variable ! is e7uivalent to _&nv.!, which in turn is e7uivalent to
<ettable=e7ent(=en7' .5.
where _&nv is the environment of the running function. ("ee BA.9 for a complete description of the g&ttabl&_&v&nt function. *his function is not defined or callable in Lua. "imilarly, the _&nv variable is not defined in Lua. :e use them here only for explanatory purposes.$
2.# - $tate%ents
Lua supports an almost conventional set of statements, similar to those in Fascal or C. *his set includes assignment, control structures, function calls, and variable declarations. 2.#.1 - Chun&s *he unit of execution of Lua is called a chunk. chun) is simply a se7uence of statements, which are executed se7uentially. ?ach statement can be optionally followed by a semicolon(
chunk &&= !stat #:;;$"
*here are no empty statements and thus ,.., is not legal. Lua handles a chun) as the body of an anonymous function with a variable number of arguments (see BA.C.=$. s such, chun)s can define local variables, receive arguments, and return values. chun) may be stored in a file or in a string inside the host program. :hen a chun) is executed, first it is precompiled into instructions for a virtual machine, and then the compiled code is executed by an interpreter for the virtual machine. Chun)s may also be pre-compiled into binary form; see program lua# for details. Frograms in source and compiled forms are interchangeable; Lua automatically detects the file type and acts accordingly. 2.#.2 - 'loc&s bloc) is a list of statements; syntactically, a bloc) is the same as a chun)(
block &&= chunk
?xplicit bloc)s are useful to control the scope of variable declarations. ?xplicit bloc)s are also sometimes used to add a return or brea" statement in the middle of another bloc) (see BA.<.<$. 2.#.! - (ssign%ent Lua allows multiple assignment. *herefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. *he elements in both lists are separated by commas(
stat &&= 7arlist+ :=; e5plist+ 7arlist+ &&= 7ar !:,; 7ar" e5plist+ &&= e5p !:,; e5p"
?xpressions are discussed in BA.C. %efore the assignment, the list of values is ad"usted 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 nil,s as needed. If the list of expressions ends with a function call, then all values returned by this call enter in the list of values, before the adjustment (except when the call is enclosed in parentheses; see BA.C$. *he assignment statement first evaluates all its expressions and only then are the assignments performed. *hus the code
i = i' a#i$ = i++' ,1
sets a[/] to A1, without affecting a[0] because the * in a[*] is evaluated (to J$ before it is assigned <. "imilarly, the line
5' > = >' 5
exchanges the values of ! and '. *he meaning of assignments to global variables and table fields can be changed via metatables. n assignment to an indexed variable t[*]1=1val is e7uivalent to )&ttabl&_&v&nt+t,*,val-. ("ee BA.9 for a complete description of the )&ttabl&_&v&nt function. *his function is not defined or callable in Lua. :e use it here only for explanatory purposes.$ n assignment to a global variable !1=1val is e7uivalent to the assignment _&nv.!1=1val, which in turn is e7uivalent to
settable=e7ent(=en7' .5.' 7al
where _&nv is the environment of the running function. (*he _&nv variable is not defined in Lua. :e use it here only for explanatory purposes.$ 2.#.# - Control $tructures *he control structures i%, #hile, and re&eat have the usual meaning and familiar syntax(
stat &&= while e5p do block end stat &&= repeat block until e5p stat &&= if e5p then block !elseif e5p then block" #else block$ end
Lua also has a %or statement, in two flavors (see BA.<.C$. *he condition expression of a control structure may return any value. %oth %alse and nil are considered false. ll values different from nil and %alse are considered true (in particular, the number 1 and the empty string are also true$. In the re&eatLuntil loop, the inner bloc) does not end at the until )eyword, but only after the condition. "o, the condition can refer to local variables declared inside the loop bloc). *he return statement is used to return values from a function or a chun) (which is just a function$. -unctions and chun)s may return more than one value, so the syntax for the return statement is
stat &&= return #e5plist+$
*he brea" statement is used to terminate the execution of a #hile, re&eat, or %or loop, s)ipping to the next statement after the loop(
stat &&= break
brea" ends the innermost enclosing loop. *he return and brea" statements can only be written as the last statement of a bloc). If it is really necessary to return or brea" in the middle of a bloc), then an explicit inner bloc) can be used, as in the idioms do1r&turn1 &nd and do1br&a21&nd, because now return and brea" are the last statements in their (inner$ bloc)s. 2.#.5 - )or $tate%ent *he %or statement has two forms( one numeric and one generic. *he numeric %or loop repeats a bloc) of code while a control variable runs through an arithmetic progression. It has the following syntax(
-C-
stat &&= for 8a9e :=; e5p :,; e5p #:,; e5p$ do block end
*he block is repeated for name starting at the value of the first e#p, until it passes the second e#p by steps of the third e#p. 8ore precisely, a %or statement li)e
for 7 = e1' e2' e3 do block end
do
ll three control expressions are evaluated only once, before the loop starts. *hey must all result in numbers. var, limit, and step are invisible variables. *he names are here for explanatory purposes only. If the third expression (the step$ is absent, then a step of 6 is used. Kou can use brea" to exit a %or loop. *he loop variable v is local to the loop; you cannot use its value after the %or ends or is bro)en. If you need this value, assign it to another variable before brea)ing or exiting the loop.
*he generic %or statement wor)s over functions, called iterators. @n each iteration, the iterator function is called to produce a new value, stopping when this new value is nil. *he generic %or loop has the following syntax(
stat &&= for na9elist in e5plist+ do block end na9elist &&= 8a9e !:,; 8a9e"
e#plist is evaluated only once. Its results are an iterator function, a state, and an initial value for the first iterator variable. f, s, and var are invisible variables. *he names are here for explanatory purposes only. Kou can use brea" to exit a %or loop. *he loop variables var$i are local to the loop; you cannot use their values after the %or ends. If you need these values, then assign them to other variables before brea)ing or exiting the loop.
2.#.* - )unction Calls as $tate%ents *o allow possible side-effects, function calls can be executed as statements(
stat &&= functioncall
In this case, all returned values are thrown away. -unction calls are explained in BA.C.9.
-I-
2.#.+ - Local ,eclarations Local variables may be declared anywhere inside a bloc). *he declaration may include an initial assignment(
stat &&= local na9elist #:=; e5plist+$
If present, an initial assignment has the same semantics of a multiple assignment (see BA.<.J$. @therwise, all variables are initiali+ed with nil. chun) is also a bloc) (see BA.<.6$, and so local variables can be declared in a chun) outside any explicit bloc). *he scope of such local variables extends until the end of the chun). *he visibility rules for local variables are explained in BA.I.
2.5 - -x ressions
*he basic expressions in Lua are the following(
e5p &&= prefi5e5p e5p &&= nil @ false @ true e5p &&= 8u9ber e5p &&= Atrin< e5p &&= function e5p &&= tableconstructor e5p &&= :...; e5p &&= e5p binop e5p e5p &&= unop e5p prefi5e5p &&= 7ar @ functioncall @ :(; e5p :);
!umbers and literal strings are explained in BA.6; variables are explained in BA.J; function definitions are explained in BA.C.=; function calls are explained in BA.C.9; table constructors are explained in BA.C.>. Hararg expressions, denoted by three dots (,...,$, can only be used when directly inside a vararg function; they are explained in BA.C.=. %inary operators comprise arithmetic operators (see BA.C.6$, relational operators (see BA.C.A$, logical operators (see BA.C.J$, and the concatenation operator (see BA.C.<$. Enary operators comprise the unary minus (see BA.C.6$, the unary not (see BA.C.J$, and the unary length operator (see BA.C.C$. %oth function calls and vararg expressions may result in multiple values. If the expression is used as a statement (see BA.<.I$ (only possible for function calls$, then its return list is adjusted to +ero elements, thus discarding all returned values. If the 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. Dere are some examples(
f( <(f( ' 5 <(5' f( a'b'c = f( ' 5 a'b = ((( ---------------adBusted to 1 results f( is adBusted to + result < <ets 5 plus all results fro9 f( f( is adBusted to + result (c <ets nil a <ets the first 7arar< para9eter' b <ets the second (both a and b 9a> <et nil if there is no correspondin< 7arar< para9eter f( is adBusted to , results f( is adBusted to - results returns all results fro9 f( returns all recei7ed 7arar< para9eters returns 5' >' and all results fro9 f( creates a list with all results fro9 f( creates a list with all 7arar< para9eters f( is adBusted to + result
a'b'c = 5' f( a'b'c = f( return f( return ((( return 5'>'f( !f( " !(((" !f( ' nil"
n expression enclosed in parentheses always results in only one value. *hus, +f+!,',3-- is always a single value, even if f returns several values. (*he value of +f+!,',3-- is the first value returned by f or nil if f does not return any values.$
->-
2.5.1 - (rith%etic . erators Lua supports the usual arithmetic operators( the binary 4 (addition$, " (subtraction$, 5 (multiplication$, 61 (division$, 7 (modulo$, and 8 (exponentiation$; and unary " (negation$. If the operands are numbers, or strings that can be converted to numbers (see BA.A.6$, then all operations have the usual meaning. ?xponentiation wor)s for any exponent. -or instance, !8+"0.9- computes the inverse of the s7uare root of !. 8odulo is defined as
a % b == a - 9ath(floor(a/b *b
*hat is, it is the remainder of a division that rounds the 7uotient towards minus infinity. 2.5.2 - Relational . erators *he relational operators in Lua are
== ~= < > <= >=
*hese operators always result in %alse or true. ?7uality (==$ first compares the type of its operands. If the types are different, then the result is %alse. @therwise, the values of the operands are compared. !umbers and strings are compared in the usual way. @bjects (tables, userdata, threads, and functions$ are compared by reference( two objects are considered e7ual only if they are the same object. ?very time you create a new object (a table, userdata, thread, or function$, this new object is different from any previously existing object. Kou can change the way that Lua compares tables and userdata by using the &e7' metamethod (see BA.9$. *he conversion rules of BA.A.6 do not apply to e7uality comparisons. *hus, "0"==0 evaluates to %alse, and t[0]1 and t["0"] denote different entries in a table. *he operator := is exactly the negation of e7uality (==$. *he order operators wor) as follows. If both arguments are numbers, then they are compared as such. @therwise, if both arguments are strings, then their values are compared according to the current locale. @therwise, Lua tries to call the <' or the &le' metamethod (see BA.9$. 2.5.! - Logical . erators *he logical operators in Lua are and, or, and not. Li)e the control structures (see BA.<.<$, all logical operators consider both %alse and nil as false and anything else as true. *he negation operator not always returns %alse or true. *he conjunction operator and returns its first argument if this value is %alse or nil; otherwise, and returns its second argument. *he disjunction operator or returns its first argument if this value is different from nil and %alse; otherwise, or returns its second argument. %oth and and or use short-cut evaluation; that is, the second operand is evaluated only if necessary. Dere are some examples(
+1 or ,1 +1 or error( nil or .a. nil and +1 false and error( false and nil false or nil +1 and ,1 --> --> --> --> --> --> --> --> +1 +1 .a. nil false false nil ,1
(In this manual, --M indicates the result of the preceding expression.$ 2.5.# - Concatenation *he string concatenation operator in Lua is denoted by two dots (,..,$. If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in BA.A.6. @therwise, the &concat' metamethod is called (see BA.9$. 2.5.5 - The Length . erator *he length operator is denoted by the unary operator ;. *he length of a string is its number of bytes (that is, the
-9-
usual meaning of string length when each character is one byte$. *he length of a table t is defined to be any integer index n such that t[n] is not nil and t[n4 ] is nil; moreover, if t[ ] is nil, n may be +ero. -or a regular array, with non-nil values from 6 to a given n, its length is exactly that n, the index of its last value. If the array has &holes' (that is, nil values between other non-nil values$, then ;t may be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array$. 2.5.* - /recedence @perator precedence in Lua follows the table below, from lower to higher priority(
or and < (( + * not ^
> / #
<=
>=
~=
==
% - (unar>
s usual, you can use parentheses to change the precedences of an expression. *he concatenation (,..,$ and exponentiation (,8,$ operators are right associative. ll other binary operators are left associative. 2.5.+ - Ta"le Constructors *able constructors are expressions that create tables. ?very time a constructor is evaluated, a new table is created. Constructors can be used to create empty tables, or to create a table and initiali+e some of its fields. *he general syntax for constructors is
tableconstructor &&= :{; #fieldlist$ :}; fieldlist &&= field !fieldsep field" #fieldsep$ field &&= :[; e5p :]; :=; e5p @ 8a9e :=; e5p @ e5p fieldsep &&= :,; @ :;;
?ach field of the form [&!( ]1=1&!(< adds to the new table an entry with )ey &!( and value &!(<. field of the form na%&1=1&!( is e7uivalent to ["na%&"]1=1&!(. -inally, fields of the form &!( are e7uivalent to [*]1 =1&!(, where * are consecutive numerical integers, starting with 6. -ields in the other formats do not affect this counting. -or example,
a = ! #f(+ $ = <% .5.' .>.% 5 = +' f(5 ' #-1$ = ,-% 26 "
is e7uivalent to
do local t = !" t#f(+ $ = < t#+$ = .5. t#,$ = .>. t(5 = + t#-$ = f(5 t#-1$ = ,t#2$ = 26 a = t end
-----
-- 2th e5p
If the last field in the list has the form &!( and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see BA.C.9$. *o avoid this, enclose the function call (or the vararg expression$ in parentheses (see BA.C$. *he field list may have an optional trailing separator, as a convenience for machine-generated code. 2.5.0 - )unction Calls function call in Lua has the following syntax(
-=-
In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type function, then this function is called with the given arguments. @therwise, the prefixexp &call' metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see BA.9$. *he form
functioncall &&= prefi5e5p ::; 8a9e ar<s
ll argument expressions are evaluated before the call. call of the form f>fields? is syntactic sugar for f+>fields?-; that is, the argument list is a single new table. call of the form f'string' (or f"string" or f[[string]]$ is syntactic sugar for f+'string'-; that is, the argument list is a single literal string. s an exception to the free-format syntax of Lua, you cannot put a line brea) before the ,+, in a function call. *his restriction avoids some ambiguities in the language. If you write
a = f (< (5(a
Lua would see that as a single statement, a1=1f+g-.!+a-. "o, if you want two statements, you must add a semi-colon between them. If you actually want to call f, you must remove the line brea) before +g-. call of the form r&turn functioncall is called a tail call. Lua implements proper tail calls (or proper tail recursion$( in a tail call, the called function reuses the stac) entry of the calling function. *herefore, there is no limit on the number of nested tail calls that a program can execute. Dowever, a tail call erases any debug information about the calling function. !ote that a tail call only happens with a particular syntax, where the return has one single function call as argument; this syntax ma)es the calling function return exactly the returns of the called function. "o, none of the following examples are tail calls(
return (f(5 return , * f(5 return 5' f(5 f(5 % return return 5 or f(5 -- results adBusted to + -- additional results -- results discarded -- results adBusted to +
*he statement
function f ( body end
translates to
f = function ( body end
*he statement
- 61 -
function t(a(b(c(f (
body end
translates to
t(a(b(c(f = function ( body end
*he statement
local function f ( body end
translates to
local f% f = function ( body end
not to
local f = function ( body end
(*his only ma)es a difference when the body of the function contains references to f.$ function definition is an executable expression, whose value has type function. :hen Lua pre-compiles a chun), all its function bodies are pre-compiled too. *hen, whenever Lua executes the function definition, the function is instantiated (or closed$. *his function instance (or closure$ is the final value of the expression. Gifferent instances of the same function may refer to different external local variables and may have different environment tables. Farameters act as local variables that are initiali+ed with the argument values(
parlist+ &&= na9elist #:,; :...;$ @ :...;
:hen 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 vararg function, which is indicated by three dots (,...,$ at the end of its parameter list. vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a vararg e#pression, which is also written as three dots. *he 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 the call is enclosed in parentheses$. s an example, consider the following definitions(
function f(a' b end function <(a' b' ((( end function r( return +','- end
*hen, we have the following mapping from arguments to parameters and to the vararg expression(
CDEE f(f(-' 2 f(-' 2' 6 f(r( ' +1 f(r( <(<(-' 2 <(-' 2' 6' J <(6' r( FDGDH4I4GA a=-' a=-' a=-' a=+' a=+' a=-' a=-' a=-' a=6' b=nil b=2 b=2 b=+1 b=, b=nil' b=2' b=2' b=+' ((( ((( ((( ((( --> --> --> --> (nothin< (nothin< 6 J , -
.esults are returned using the return statement (see BA.<.<$. If control reaches the end of a function without encountering a return statement, then the function returns with no results. *he colon syntax is used for defining methods, that is, functions that have an implicit extra parameter )&lf. *hus, the statement
function t(a(b(c&f (params body end
- 66 -
!otice that, in a declaration li)e lo#al1!1=1!, the new ! being declared is not in scope yet, and so the second ! refers to the outside variable. %ecause of the lexical scoping rules, local variables can be freely accessed by functions defined inside their scope. local variable used by an inner function is called an upvalue, or e#ternal local variable, inside the inner function. !otice that each execution of a local statement defines new local variables. Consider the following example(
a = !" local 5 = ,1 for i=+'+1 do local > = 1 a#i$ = function ( end
*he loop creates ten closures (that is, ten instances of the anonymous function$. ?ach of these closures uses a different ' variable, while all of them share the same !.
2.0 - Metata"les
?very value in Lua may have a metatable. *his metatable is an ordinary Lua table that defines the behavior of the original value under certain special operations. Kou can change several aspects of the behavior of operations over a value by setting specific fields in its metatable. -or instance, when a non-numeric value is the operand of an addition, Lua chec)s for a function in the field "__add" in its metatable. If it finds one, Lua calls this function to perform the addition. :e call the )eys in a metatable events and the values metamethods. In the previous example, the event is "add"1 and the metamethod is the function that performs the addition. Kou can 7uery the metatable of any value through the g&t%&tatabl& function. Kou can replace the metatable of tables through the )&t%&tatabl& function. Kou cannot change the metatable of other types from Lua (except using the debug library$; you must use the C FI for that.
- 6A -
*ables and userdata have individual metatables (although multiple tables and userdata can share their metatables$; values of all other types share one single metatable per type. "o, there is one single metatable for all numbers, and for all strings, etc. metatable may control how an object behaves in arithmetic operations, order comparisons, concatenation, length operation, and indexing. metatable can also define a function to be called when a userdata is garbage collected. -or each of these operations Lua associates a specific )ey called an event. :hen Lua performs one of these operations over a value, it chec)s whether this value has a metatable with the corresponding event. If so, the value associated with that )ey (the metamethod$ controls how Lua will perform the operation. 8etatables control the operations listed next. ?ach operation is identified by its corresponding name. *he )ey for each operation is a string with its name prefixed by two underscores, ,__,; for instance, the )ey for operation &add' is the string "__add". *he semantics of these operations is better explained by a Lua function describing how the interpreter executes the operation. *he 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. ll functions used in these descriptions (rawg&t, tonu%b&r, etc.$ are described in BC.6. In particular, to retrieve the metamethod of a given object, we use the expression
9etatable(obB #e7ent$
*hat is, the access to a metamethod does not invo)e other metamethods, and the access to objects with no metatables does not fail (it simply results in nil$.
'add() the 4 operation. *he function g&tb*n$andl&r below defines how Lua chooses a handler for a binary operation. -irst, Lua tries the first operand. If its type does not define a handler for the operation, then Lua tries the second operand.
function <etbinhandler (op+' op,' e7ent return 9etatable(op+ #e7ent$ or 9etatable(op, #e7ent$ end
'sub() the " operation. %ehavior similar to the &add' operation. 'mul() the 5 operation. %ehavior similar to the &add' operation. 'di*() the 6 operation. %ehavior similar to the &add' operation. 'mod() the 7 operation. %ehavior similar to the &add' operation, with the operation o 1"1 floor+o 6o<-5o< as the primitive operation. '&o#() the 8 (exponentiation$ operation. %ehavior similar to the &add' operation, with the function (ow1 (from the C math library$ as the primitive operation. 'unm() the unary " operation.
function un9=e7ent (op local o = tonu9ber(op - 6J -
if o then -- operand is nu9ericK return -o -- )-) here is the pri9iti7e )un9) else -- the operand is not nu9eric( -- Ir> to <et a handler fro9 the operand local h = 9etatable(op (==un9 if h then -- call the handler with the operand return h(op else -- no handler a7ailable& default beha7ior error(??? end end end
'eq() the == operation. *he function g&t#o%($andl&r defines how Lua chooses a metamethod for comparison operators. metamethod only is selected when both objects being compared have the same type and the same metamethod for the selected operation.
function <etco9phandler (op+' op,' e7ent if t>pe(op+ ~= t>pe(op, then return nil end local 99+ = 9etatable(op+ #e7ent$ local 99, = 9etatable(op, #e7ent$ if 99+ == 99, then return 99+ else return nil end end
return true -- obBects are eLual end -- tr> 9eta9ethod local h = <etco9phandler(op+' op,' .==eL. if h then return h(op+' op, else return false end end
a1A=1b is e7uivalent to b1@=1a. !ote that, in the absence of a &le' metamethod, Lua tries the <', assuming that a1@=1b is e7uivalent to not1+b1@1a-.
h = 9etatable(table (==inde5 if h == nil then error(??? % end end if t>pe(h == .function. then return h(table' ke> -- call the handler else return h#ke>$ -- or repeat operation on it end end
2.1 - -nviron%ents
%esides metatables, objects of types thread, function, and userdata have another table associated with them, called their environment. Li)e metatables, environments are regular tables and multiple objects can share the same environment. ?nvironments associated with userdata have no meaning for Lua. It is only a convenience feature for programmers to associate a table to a userdata. ?nvironments associated with threads are called global environments. *hey are used as the default environment for their threads and non-nested functions created by the thread (through loadf*l&, load)tr*ng or load$ and can be directly accessed by C code (see BJ.J$. ?nvironments associated with C functions can be directly accessed by C code (see BJ.J$. *hey are used as the default environment for other C functions created by the function. ?nvironments associated with Lua functions are used to resolve all accesses to global variables within the function (see BA.J$. *hey are used as the default environment for other Lua functions created by the function.
- 6I -
Kou can change the environment of a Lua function or the running thread by calling )&tf&nv. Kou can get the environment of a Lua function or the running thread by calling g&tf&nv. *o manipulate the environment of other objects (userdata, C functions, other threads$ you must use the C FI.
t the end of each garbage-collection cycle, the finali+ers for userdata are called in reverse order of their creation, among those collected in that cycle. *hat is, the first finali+er to be called is the one associated with the userdata created last in the program. 2.13.2 - 5ea& Ta"les weak table is a table whose elements are weak references. wea) reference is ignored by the garbage collector. In other words, if the only references to an object are wea) references, then the garbage collector will collect this object. wea) table can have wea) )eys, wea) values, or both. table with wea) )eys allows the collection of its )eys, but prevents the collection of its values. table with both wea) )eys and wea) values allows the collection of both )eys and values. In any case, if either the )ey or the value is collected, the whole pair is removed from the table. *he wea)ness of a table is controlled by the __%od& field of its metatable. If the __%od& field is a string containing the character ,2,, the )eys in the table are wea). If __%od& contains ,v,, the values in the table are wea). fter you use a table as a metatable, you should not change the value of its field __%od&. @therwise, the wea) behavior of the tables controlled by this metatable is undefined.
- 6> -
2.11 - Coroutines
Lua supports coroutines, also called collaborative multithreading. coroutine in Lua represents an independent thread of execution. Enli)e threads in multithread systems, however, a coroutine only suspends its execution by explicitly calling a yield function. Kou create a coroutine with a call to #orout*n&.#r&at&. Its sole argument is a function that is the main function of the coroutine. *he #r&at& function only creates a new coroutine and returns a handle to it (an object of type thread$; it does not start the coroutine execution. :hen you first call #orout*n&.r&)u%&, passing as its first argument the thread returned by #orout*n&.#r&at&, the coroutine starts its execution, at the first line of its main function. ?xtra arguments passed to #orout*n&.r&)u%& are passed on to the coroutine main function. fter the coroutine starts running, it runs until it terminates or yields. 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, #orout*n&.r&)u%& returns true, plus any values returned by the coroutine main function. In case of errors, #orout*n&.r&)u%& returns %alse plus an error message. coroutine yields by calling #orout*n&.'*&ld. :hen a coroutine yields, the corresponding #orout*n&.r&)u%& 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, #orout*n&.r&)u%& also returns true, plus any values passed to #orout*n&.'*&ld. *he next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to #orout*n&.'*&ld returning any extra arguments passed to #orout*n&.r&)u%&. Li)e #orout*n&.#r&at&, the #orout*n&.wra( function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. ny arguments passed to this function go as extra arguments to #orout*n&.r&)u%&. #orout*n&.wra( returns all the values returned by #orout*n&.r&)u%&, except the first one (the boolean error code$. Enli)e #orout*n&.r&)u%&, #orout*n&.wra( does not catch errors; any error is propagated to the caller. s an example, consider the following code(
function foo (a print(.foo.' a return coroutine(>ield(,*a end co = coroutine(create(function (a'b print(.co-bod>.' a' b local r = foo(a++ print(.co-bod>.' r local r' s = coroutine(>ield(a+b' a-b print(.co-bod>.' r' s return b' .end. end print(.9ain.' print(.9ain.' print(.9ain.' print(.9ain.' coroutine(resu9e(co' coroutine(resu9e(co' coroutine(resu9e(co' coroutine(resu9e(co' +' +1 .r. .5.' .>. .5.' .>.
laststat ((P funcname ((P varlist6 ((P var ((P namelist ((P explist6 ((P exp ((P prefixexp ((P functioncall ((P args ((P function ((P funcbody ((P parlist6 ((P tableconstructor ((P fieldlist ((P field ((P fieldsep ((P binop ((P unop ((P
- 6= -