Copyright (C) 2000-2012 |
Whole document tree Reference Manual of the Programming Language Lua 4.0
1 - IntroductionLua is an extension programming language designed to support general procedural programming with data description facilities. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in C. Being an extension language, Lua has no notion of a ``main'' program: it only works embedded in a host client, called the embedding program. This host program can invoke functions to execute a piece of code in Lua, can write and read Lua variables, and can register C functions to be called by Lua code. Through the use of C functions, Lua can be augmented to cope with a wide range of different domains, thus creating customized programming languages sharing a syntactical framework. Lua is free-distribution software, and is provided as usual with no guarantees, as stated in its copyright notice. The implementation described in this manual is available at the following URL's: http://www.tecgraf.puc-rio.br/lua/ ftp://ftp.tecgraf.puc-rio.br/pub/lua/ Like any other reference manual, this document is dry in places. For a discussion of the decisions behind the design of Lua, see the papers below, which are available at the web site above.
2 - Environment and Chunks
All statements in Lua are executed in a global environment.
This environment is initialized with a call from the embedding program to
The global environment can be manipulated by Lua code or by the embedding program, which can read and write global variables using API functions from the library that implements Lua. Global variables in Lua do not need to be declared. Any variable is assumed to be global unless explicitly declared local (see Section 4.4.6). Before the first assignment, the value of a global variable is nil (this default can be changed; see Section 4.8). A table is used to keep all global names and values (tables are explained in Section 3). The unit of execution of Lua is called a chunk. A chunk is simply a sequence of statements, which are executed sequentially. Each statement can be optionally followed by a semicolon: chunk ::= {stat [`;']}Statements are described in Section 4.4. (The notation above is the usual extended BNF, in which {a} means 0 or more a's, [a] means an optional a, and (a)+ means one or more a's. The complete syntax of Lua is given in BNF). A chunk may be stored in a file or in a string inside the host program. When a chunk is executed, first it is pre-compiled into bytecodes for a virtual machine, and then the statements are executed in sequential order, by simulating the virtual machine. All modifications a chunk effects on the global environment persist after the chunk ends. Chunks may also be pre-compiled into binary form and stored in files; see program luac for details. Text files with chunks and their binary pre-compiled forms are interchangeable. Lua automatically detects the file type and acts accordingly. 3 - Types and TagsLua is a dynamically typed language. This means that variables do not have types; only values do. Therefore, there are no type definitions in the language. All values carry their own type. Besides a type, all values also have a tag.
There are six basic types in Lua: nil, number,
string, function, userdata, and table.
Nil is the type of the value nil,
whose main property is to be different from any other value.
Number represents real (double-precision floating-point) numbers,
while string has the usual meaning.
Lua is 8-bit clean,
and so strings may contain any 8-bit character,
including embedded zeros (
Functions are considered first-class values in Lua.
This means that functions can be stored in variables,
passed as arguments to other functions, and returned as results.
Lua can call (and manipulate) functions written in Lua and
functions written in C.
The two kinds of functions can be distinguished by their tags:
all Lua functions have the same tag,
and all C functions have the same tag,
which is different from the tag of Lua functions.
The
The type userdata is provided to allow
arbitrary C pointers to be stored in Lua variables.
This type corresponds to a
The type table implements associative arrays,
that is, arrays that can be indexed not only with numbers,
but with any value (except nil).
Therefore, this type may be used not only to represent ordinary arrays,
but also symbol tables, sets, records, graphs, trees, etc.
Tables are the main data structuring mechanism in Lua.
To represent records, Lua uses the field name as an index.
The language supports this representation by
providing Note that tables are objects, and not values. Variables do not contain tables, only references to them. Assignment, parameter passing, and returns always manipulate references to tables, and do not imply any kind of copy. Moreover, tables must be explicitly created before used (see Section 4.5.7).
Each of the types nil, number, and string has a different tag.
All values of each of these types have the same pre-defined tag.
As explained above,
values of type function can have two different tags,
depending on whether they are Lua functions or C functions.
Finally,
values of type userdata and table can have variable tags,
assigned by the programmer (see Section 4.8).
The
4 - The LanguageThis section describes the lexis, the syntax, and the semantics of Lua.
4.1 - Lexical ConventionsIdentifiers in Lua can be any string of letters, digits, and underscores, not beginning with a digit. This coincides with the definition of identifiers in most languages, except that the definition of letter depends on the current locale: Any character considered alphabetic by the current locale can be used in an identifier. The following words are reserved, and cannot be used as identifiers: and break do else elseif end for function if in local nil not or repeat return then until while
Lua is a case-sensitive language:
and is a reserved word, but And and ánd
(if the locale permits) are two different, valid identifiers.
As a convention, identifiers starting with underscore followed by
uppercase letters (such as The following strings denote other tokens: ~= <= >= < > == = + - * / ( ) { } [ ] ; , . .. ...
Literal strings
can be delimited by matching single or double quotes,
and can contain the C-like escape sequences
`
Literal strings can also be delimited by matching 1) "alo\n123\"" 2) '\97lo\10\04923"' 3) [[alo 123"]]
Comments start anywhere outside a string with a
double hyphen ( Numerical constants may be written with an optional decimal part and an optional decimal exponent. Examples of valid numerical constants are 3 3.0 3.1416 314.16e-2 0.31416E1 4.2 - Coercion
Lua provides some automatic conversions between values at run time.
Any arithmetic operation applied to a string tries to convert
that string to a number, following the usual rules.
Conversely, whenever a number is used when a string is expected,
that number is converted to a string, in a reasonable format.
The format is chosen so that
a conversion from number to string then back to number
reproduces the original number exactly.
Thus,
the conversion does not necessarily produces nice-looking text for some numbers.
For complete control of how numbers are converted to strings,
use the
4.3 - AdjustmentFunctions in Lua can return many values. Because there are no type declarations, when a function is called the system does not know how many values the function will return, or how many parameters it needs. Therefore, sometimes, a list of values must be adjusted, at run time, to a given length. If there are more values than are needed, then the excess values are thrown away. If there are less values than are needed, then the list is extended with as many nil's as needed. This adjustment occurs in multiple assignments (see Section 4.4.2) and in function calls (see Section 4.5.8).
4.4 - StatementsLua supports an almost conventional set of statements, similar to those in Pascal or C. The conventional commands include assignment, control structures, and procedure calls. Non-conventional commands include table constructors (see Section 4.5.7) and local variable declarations (see Section 4.4.6).
4.4.1 - BlocksA block is a list of statements; syntactically, a block is equal to a chunk:block ::= chunk A block may be explicitly delimited: stat ::= do block endExplicit blocks are useful to control the scope of local variables (see Section 4.4.6). Explicit blocks are also sometimes used to add a return or break statement in the middle of another block (see Section 4.4.3). 4.4.2 - AssignmentLua allows multiple assignment. 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:stat ::= varlist1 `=' explist1 varlist1 ::= var {`,' var}This statement first evaluates all values on the right side and eventual indices on the left side, and then makes the assignments. So, the code i = 3 i, a[i] = 4, 20sets a[3] to 20, but does not affect a[4]
because the i in a[i] is evaluated
before it is assigned 4 .
Multiple assignment can be used to exchange two values, as in x, y = y, x The two lists in a multiple assignment may have different lengths. Before the assignment, the list of values is adjusted to the length of the list of variables (see Section 4.3). A single name can denote a global variable, a local variable, or a formal parameter: var ::= name Square brackets are used to index a table: var ::= varorfunc `[' exp1 `]' varorfunc ::= var | functioncallThe varorfunc should result in a table value, from where the field indexed by the expression exp1 value gets the assigned value.
The syntax var ::= varorfunc `.' name
The meaning of assignments and evaluations of global variables and
indexed variables can be changed by tag methods (see Section 4.8).
Actually,
an assignment 4.4.3 - Control StructuresThe control structures if, while, and repeat have the usual meaning and familiar syntaxstat ::= while exp1 do block end stat ::= repeat block until exp1 stat ::= if exp1 then block {elseif exp1 then block} [else block] endThe condition expression exp1 of a control structure may return any value. All values different from nil are considered true; only nil is considered false. The return statement is used to return values from a function or from a chunk. Because functions or chunks may return more than one value, the syntax for the return statement is stat ::= return [explist1] The break statement can be used to terminate the execution of a loop, skipping to the next statement after the loop: stat ::= breakA break ends the innermost enclosing loop (while, repeat, or for).
For syntactic reasons, return and break
statements can only be written as the last statements of a block.
If it is really necessary to return or break in the
middle of a block,
an explicit inner block can used,
as in the idiom ` 4.4.4 - For StatementThe for statement has two forms, one for numbers and one for tables. The numerical for loop has the following syntax: stat ::= for name `=' exp1 `,' exp1 [`,' exp1] do block endA for statement like for var = e1 ,e2, e3 do block endis equivalent to the code: do local var, _limit, _step = tonumber(e1), tonumber(e2), tonumber(e3) if not (var and _limit and _step) then error() end while (_step>0 and var<=_limit) or (_step<=0 and var>=_limit) do block var = var+_step end endNote the following:
The table for statement traverses all pairs (index,value) of a given table. It has the following syntax: stat ::= for name `,' name in exp1 do block endA for statement like for index, value in exp do block endis equivalent to the code: do local _t = exp local index, value = next(t, nil) while index do block index, value = next(t, index) end endNote the following:
4.4.5 - Function Calls as StatementsBecause of possible side-effects, function calls can be executed as statements:stat ::= functioncallIn this case, all returned values are thrown away. Function calls are explained in Section 4.5.8. 4.4.6 - Local DeclarationsLocal variables may be declared anywhere inside a block. The declaration may include an initial assignment:stat ::= local declist [init] declist ::= name {`,' name} init ::= `=' explist1If present, an initial assignment has the same semantics of a multiple assignment. Otherwise, all variables are initialized with nil. A chunk is also a block, and so local variables can be declared outside any explicit block.
The scope of local variables begins after
the declaration and lasts until the end of the block.
Thus, the code
4.5 - Expressions
4.5.1 - Basic ExpressionsThe basic expressions in Lua areexp ::= `(' exp `)' exp ::= nil exp ::= number exp ::= literal exp ::= var exp ::= upvalue exp ::= function exp ::= functioncall exp ::= tableconstructor Numbers (numerical constants) and literal strings are explained in Section 4.1; variables are explained in Section 4.4.2; upvalues are explained in Section 4.6; function definitions are explained in Section 4.5.9; function calls are explained in Section 4.5.8. Table constructors are explained in Section 4.5.7.
An access to a global variable The non-terminal exp1 is used to indicate that the values returned by an expression must be adjusted to one single value: exp1 ::= exp
4.5.2 - Arithmetic OperatorsLua supports the usual arithmetic operators: the binary+ (addition),
- (subtraction), * (multiplication),
/ (division), and ^ (exponentiation);
and unary - (negation).
If the operands are numbers, or strings that can be converted to
numbers (according to the rules given in Section 4.2),
then all operations except exponentiation have the usual meaning.
Otherwise, an appropriate tag method is called (see Section 4.8).
An exponentiation always calls a tag method.
The standard mathematical library redefines this method for numbers,
giving the expected meaning to exponentiation
(see Section 6.3).
4.5.3 - Relational OperatorsThe relational operators in Lua are== ~= < > <= >=These operators return nil as false and a value different from nil as true.
Equality (
The conversion rules of Section 4.2
do not apply to equality comparisons.
Thus, 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 using lexicographical order. Otherwise, the ``lt'' tag method is called (see Section 4.8).
4.5.4 - Logical OperatorsThe logical operators in Lua areand or notLike the control structures, all logical operators consider nil as false and anything else as true.
The conjunction operator There are two useful Lua idioms that use logical operators. The first idiom is x = x or vwhich is equivalent to if x == nil then x = v endThis idiom sets x to a default value v when x is not set.
The second idiom is x = a and b or cwhich should be read as x = (a and b) or c .
This idiom is equivalent to
if a then x = b else x = c endprovided that b is not nil.
4.5.5 - ConcatenationThe 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 in Section 4.2. Otherwise, the ``concat'' tag method is called (see Section 4.8).
4.5.6 - PrecedenceOperator precedence in Lua follows the table below, from the lower to the higher priority:and or < > <= >= ~= == .. + - * / not - (unary) ^All binary operators are left associative, except for ^ (exponentiation),
which is right associative.
The pre-compiler may rearrange the order of evaluation of
associative operators (such as .. or + ),
as long as these optimizations do not change normal results.
However, these optimizations may change some results
if you define non-associative
tag methods for these operators.
4.5.7 - Table ConstructorsTable constructors are expressions that create tables; every time a constructor is evaluated, a new table is created. Constructors can be used to create empty tables, or to create a table and initialize some of its fields. The general syntax for constructors istableconstructor ::= `{' fieldlist `}' fieldlist ::= lfieldlist | ffieldlist | lfieldlist `;' ffieldlist | ffieldlist `;' lfieldlist lfieldlist ::= [lfieldlist1] ffieldlist ::= [ffieldlist1] The form lfieldlist1 is used to initialize lists: lfieldlist1 ::= exp {`,' exp} [`,']The expressions in the list are assigned to consecutive numerical indices, starting with 1. For example, a = {"v1", "v2", 34}is equivalent to do local temp = {} temp[1] = "v1" temp[2] = "v2" temp[3] = 34 a = temp end The form ffieldlist1 initializes other fields in a table: ffieldlist1 ::= ffield {`,' ffield} [`,'] ffield ::= `[' exp `]' `=' exp | name `=' expFor example, a = {[f(k)] = g(y), x = 1, y = 3, [0] = b+c}is equivalent to do local temp = {} temp[f(k)] = g(y) temp.x = 1 -- or temp["x"] = 1 temp.y = 3 -- or temp["y"] = 3 temp[0] = b+c a = temp endAn expression like {x = 1, y = 4} is
in fact syntactic sugar for {["x"] = 1, ["y"] = 4} .
Both forms may have an optional trailing comma, and can be used in the same constructor separated by a semi-colon. For example, all forms below are correct. x = {;} x = {"a", "b",} x = {type="list"; "a", "b"} x = {f(0), f(1), f(2),; n=3,} 4.5.8 - Function CallsA function call in Lua has the following syntax:functioncall ::= varorfunc argsFirst, varorfunc is evaluated. If its value has type function, then this function is called, with the given arguments. Otherwise, the ``function'' tag method is called, having as first parameter the value of varorfunc, and then the original call arguments (see Section 4.8). The form functioncall ::= varorfunc `:' name argscan be used to call ``methods''. A call v:name(...)
is syntactic sugar for v.name(v, ...) ,
except that v is evaluated only once.
Arguments have the following syntax: args ::= `(' [explist1] `)' args ::= tableconstructor args ::= literal explist1 ::= {exp1 `,'} expAll argument expressions are evaluated before the call. A call of the form f{...} is syntactic sugar for
f({...}) , that is,
the argument list is a single new table.
A call of the form f'...'
(or f"..." or f[[...]] ) is syntactic sugar for
f('...') , that is,
the argument list is a single literal string.
Because a function can return any number of results (see Section 4.4.3), the number of results must be adjusted before they are used (see Section 4.3). If the function is called as a statement (see Section 4.4.5), then its return list is adjusted to 0, thus discarding all returned values. If the function is called in a place that needs a single value (syntactically denoted by the non-terminal exp1), then its return list is adjusted to 1, thus discarding all returned values but the first one. If the function is called in a place that can hold many values (syntactically denoted by the non-terminal exp), then no adjustment is made. The only places that can hold many values is the last (or the only) expression in an assignment, in an argument list, or in the return statement. Here are some examples: f() -- adjusted to 0 results g(f(), x) -- f() is adjusted to 1 result g(x, f()) -- g gets x plus all values returned by f() a,b,c = f(), x -- f() is adjusted to 1 result (and c gets nil) a,b,c = x, f() -- f() is adjusted to 2 a,b,c = f() -- f() is adjusted to 3 return f() -- returns all values returned by f() return x,y,f() -- returns a, b, and all values returned by f() 4.5.9 - Function DefinitionsThe syntax for function definition is function ::= function `(' [parlist1] `)' block end stat ::= function funcname `(' [parlist1] `)' block end funcname ::= name | name `.' name | name `:' nameThe statement function f () ... endis just syntactic sugar for f = function () ... endand the statement function v.f () ... endis syntactic sugar for v.f = function () ... end A function definition is an executable expression, whose value has type function. When Lua pre-compiles a chunk, all its function bodies are pre-compiled too. Then, whenever Lua executes the function definition, its upvalues are fixed (see Section 4.6), and the function is instantiated (or closed). This function instance (or closure) is the final value of the expression. Different instances of the same function may have different upvalues. Parameters act as local variables, initialized with the argument values: parlist1 ::= `...' parlist1 ::= name {`,' name} [`,' `...']When a function is called, the list of arguments is adjusted to the length of the list of parameters (see Section 4.3), unless the function is a vararg function, which is indicated by three dots (` ... ') at the end of its parameter list.
A vararg function does not adjust its argument list;
instead, it collects all extra arguments into an implicit parameter,
called arg.
The value of arg is a table,
with a field n whose value is the number of extra arguments,
and the extra arguments at positions 1, 2, ..., n .
As an example, consider the following definitions: function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 endThen, we have the following mapping from arguments to parameters: CALL PARAMETERS Results are returned using the return statement (see Section 4.4.3). If control reaches the end of a function without encountering a return statement, then the function returns with no results. The syntax funcname ::= name `:' nameis used for defining methods, that is, functions that have an implicit extra parameter self. The statement function v:f (...) ... endis just syntactic sugar for v.f = function (self, ...) ... endNote that the function gets an extra formal parameter called self .
4.6 - Visibility and UpvaluesA function body may refer to its own local variables (which include its parameters) and to global variables, as long as they are not shadowed by local variables with the same name from enclosing functions. A function cannot access a local variable from an enclosing function, since such variables may no longer exist when the function is called. However, a function may access the value of a local variable from an enclosing function, using upvalues, whose syntax is upvalue ::= `%' name An upvalue is somewhat similar to a variable expression, but whose value is frozen when the function wherein it appears is instantiated. The name used in an upvalue may be the name of any variable visible at the point where the function is defined, that is, global variables and local variables from the immediately enclosing function. Note that when the upvalue is a table, only the reference to that table (which is the value of the upvalue) is frozen; the table contents can be changed at will. Using table values as upvalues is a technique for having writable but private state attached to functions. Here are some examples: a,b,c = 1,2,3 -- global variables local d function f (x) local b = {} -- x and b are local to f; b shadows the global b local g = function (a) local y -- a and y are local to g p = a -- OK, access local `a' p = c -- OK, access global `c' p = b -- ERROR: cannot access a variable in outer scope p = %b -- OK, access frozen value of `b' (local to `f') %b = 3 -- ERROR: cannot change an upvalue %b.x = 3 -- OK, change the table contents p = %c -- OK, access frozen value of global `c' p = %y -- ERROR: `y' is not visible where `g' is defined p = %d -- ERROR: `d' is not visible where `g' is defined end -- g end -- f
4.7 - Error Handling
Because Lua is an extension language,
all Lua actions start from C code in the host program
calling a function from the Lua library.
Whenever an error occurs during Lua compilation or execution,
the function
Memory allocation errors are an exception to the previous rule.
When memory allocation fails, Lua may not be able to execute the
The only argument to
Lua code can explicitly generate an error by calling the
function
4.8 - Tag MethodsLua provides a powerful mechanism to extend its semantics, called tag methods. A tag method is a programmer-defined function that is called at specific key points during the execution of a Lua program, allowing the programmer to change the standard Lua behavior at these points. Each of these points is called an event.
The tag method called for any specific event is selected
according to the tag of the values involved
in the event (see Section 3).
The function settagmethod changes the tag method
associated with a given pair (tag, event).
Its first parameter is the tag, the second parameter is the event name
(a string; see below),
and the third parameter is the new method (a function),
or nil to restore the default behavior for the pair.
The
Tag methods are called in the following events,
identified by the given names.
The semantics of tag methods is better explained by a Lua function
describing the behavior of the interpreter at each event.
This function not only shows when a tag method is called,
but also its arguments, its results, and the default behavior.
The code shown here 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
(
5 - The Application Program InterfaceThis section describes the 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 filelua.h .
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 its arguments exactly once, and so do not generate hidden side-effects.
5.1 - States
The Lua library is fully reentrant:
it does not have any global variables.
The whole state of the Lua interpreter
(global variables, stack, tag methods, etc.)
is stored in a dynamically allocated structure of type Before calling any API function, you must create a state by calling lua_State *lua_open (int stacksize);The sole argument to this function is the stack size for the interpreter. (Each function call needs one stack position for each argument, local variable, and temporary value, plus one position for book-keeping. The stack must also have some 20 extra positions available. For very small implementations, without recursive functions, a stack size of 100 should be enough.) If stacksize is zero,
then a default size of 1024 is used.
To release a state created with void lua_close (lua_State *L);This function destroys all objects in the given Lua environment (calling the corresponding garbage-collection tag methods, if any) and frees all dynamic memory used by that state. Usually, you do not need to call this function, because all resources are naturally released when your program ends. On the other hand, long-running programs - like a daemon or a web server - might need to release states as soon as they are not needed, to avoid growing too big.
With the exception of
5.2 - The Stack and IndicesLua uses a stack to pass values to and from C. Each element in this stack represents a Lua value (nil, number, string, etc.).
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 index:
A positive index represents an absolute stack position
(starting at 1, not 0 as in C);
a negative index represents an offset from the top of the stack.
More specifically, if the stack has n elements,
index 1 represents the first element
(that is, the first element pushed onto the stack),
and
index n represents the last element;
index -1 also represents the last element
(that is, the element at the top),
and index -n represents the first element.
We say that an index is valid
if it lays between 1 and the stack top
(that is, if At any time, you can get the index of the top element by calling int lua_gettop (lua_State *L);Because indices start at 1, the result of lua_gettop is equal to the number of elements in the stack
(and so 0 means an empty stack).
When you interact with Lua API, you are responsible for controlling stack overflow. The function int lua_stackspace (lua_State *L);returns the number of stack positions still available. Whenever Lua calls C, it ensures that at least LUA_MINSTACK positions are still available.
LUA_MINSTACK is defined in lua.h and is at least 16,
and so you have to worry about stack space only
when your code has loops pushing elements onto the stack.
Most query functions accept as indices any value inside the available stack space. Such indices are called acceptable indices. More formally, we can define an acceptable index as (index < 0 && abs(index) <= top) || (index > 0 && index <= top + stackspace)Note that 0 is not an acceptable index. 5.3 - Stack ManipulationThe API offers the following functions for basic stack manipulation:void lua_settop (lua_State *L, int index); void lua_pushvalue (lua_State *L, int index); void lua_remove (lua_State *L, int index); void lua_insert (lua_State *L, int index);
#define lua_pop(L,n) lua_settop(L, -(n)-1)which pops n elements from the stack.
lua_pushvalue(L, 3) --> 10 20 30 40 50 30 lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30 lua_remove(L, -3) --> 10 20 30 40 30 30 lua_remove(L, 6) --> 10 20 30 40 30 lua_insert(L, 1) --> 30 10 20 30 40 lua_insert(L, -1) --> 30 10 20 30 40 (no effect) lua_settop(L, -3) --> 30 10 20 lua_settop(L, 6) --> 30 10 20 nil nil nil
5.4 - Querying the StackTo check the type of a stack element, the following functions are available: int lua_type (lua_State *L, int index); int lua_tag (lua_State *L, int index); int lua_isnil (lua_State *L, int index); int lua_isnumber (lua_State *L, int index); int lua_isstring (lua_State *L, int index); int lua_istable (lua_State *L, int index); int lua_isfunction (lua_State *L, int index); int lua_iscfunction (lua_State *L, int index); int lua_isuserdata (lua_State *L, int index);These functions can be called with any acceptable index.
const char *lua_typename (lua_State *L, int t);where t is a type returned by lua_type .
The strings returned by lua_typename are
"nil" , "number" , "string" , "table" ,
"function" , "userdata" , and "no value" ,
The The API also has functions to compare two values in the stack: int lua_equal (lua_State *L, int index1, int index2); int lua_lessthan (lua_State *L, int index1, int index2);These functions are equivalent to their counterparts in Lua. Specifically, lua_lessthan is equivalent to the lt_event
described in Section 4.8.
Both functions return 0 if any of the indices are non-valid.
To translate a value in the stack to a specific C type, you can use the following conversion functions: double lua_tonumber (lua_State *L, int index); const char *lua_tostring (lua_State *L, int index); size_t lua_strlen (lua_State *L, int index); lua_CFunction lua_tocfunction (lua_State *L, int index); void *lua_touserdata (lua_State *L, int index);These functions can be called with any acceptable index. When called with a non-valid index, they act as if the given value had an incorrect type.
5.5 - Pushing values onto the StackThe API has the following functions to push C values onto the stack: void lua_pushnumber (lua_State *L, double n); void lua_pushlstring (lua_State *L, const char *s, size_t len); void lua_pushstring (lua_State *L, const char *s); void lua_pushusertag (lua_State *L, void *u, int tag); void lua_pushnil (lua_State *L); void lua_pushcfunction (lua_State *L, lua_CFunction f);These functions receive a C value, convert it to a corresponding Lua value, and push the result onto the stack. In particular, lua_pushlstring and lua_pushstring
make an internal copy of the given string.
lua_pushstring can only be used to push proper C strings
(that is, strings that end with a zero and do not contain embedded zeros);
otherwise you should use the more general lua_pushlstring ,
which accepts an explicit size.
5.6 - Garbage CollectionLua uses two numbers to control its garbage collection. One number counts how many bytes of dynamic memory Lua is using, and the other is a threshold. (This internal byte counter kept by Lua is not completely acurate; it is just a lower bound, usually within 10% of the correct value.) When the number of bytes crosses the threshold, Lua runs a garbage-collection cycle, which reclaims the memory of all ``dead'' objects (that is, objects no longer accessible from Lua). The byte counter is corrected, and then the threshold is reset to twice the value of the byte counter. You can access the current values of these two numbers through the following functions: int lua_getgccount (lua_State *L); int lua_getgcthreshold (lua_State *L);Both return their respective values in Kbytes. You can change the threshold value with void lua_setgcthreshold (lua_State *L, int newthreshold);Again, the newthreshold value is given in Kbytes.
When you call this function,
Lua sets the new threshold and checks it against the byte counter.
If the new threshold is smaller than the byte counter,
then Lua immediately runs the garbage collector;
after the collection,
a new threshold is set according to the previous rule.
If you want to change the adaptative behavior of the garbage collector, you can use the garbage-collection tag method for nil to set your own threshold (the tag method is called after Lua resets the threshold).
5.7 - Userdata and Tags
Because userdata are objects,
the function Userdata can have different tags, whose semantics are only known to the host program. Tags are created with the function int lua_newtag (lua_State *L);The function lua_settag changes the tag of
the object on top of the stack (without popping it):
void lua_settag (lua_State *L, int tag);The object must be a userdata or a table; the given tag must be a value created with lua_newtag .
5.8 - Executing Lua CodeA host program can execute Lua chunks written in a file or in a string by using the following functions:int lua_dofile (lua_State *L, const char *filename); int lua_dostring (lua_State *L, const char *string); int lua_dobuffer (lua_State *L, const char *buff, size_t size, const char *name);These functions return 0 in case of success, or one of the following error codes if they fail:
lua.h .
When called with argument
The third parameter to
These functions push onto the stack
any values eventually returned by the chunk.
A chunk may return any number of values;
Lua takes care that these values fit into the stack space,
but after the call the responsibility is back to you.
If you need to push other elements after calling any of these functions,
and you want to ``play safe'',
you must either check the stack space
with { int oldtop = lua_gettop(L); lua_dofile(L, filename); lua_settop(L, oldtop); }
5.9 - Manipulating Global Variables in LuaTo read the value of a global Lua variable, you call void lua_getglobal (lua_State *L, const char *varname);which pushes onto the stack the value of the given variable. As in Lua, this function may trigger a tag method for the ``getglobal'' event (see Section 4.8). To read the real value of a global variable, without invoking any tag method, use lua_rawget over the table of globals
(see below).
To store a value in a global variable, you call void lua_setglobal (lua_State *L, const char *varname);which pops from the stack the value to be stored in the given variable. As in Lua, this function may trigger a tag method for the ``setglobal'' event (see Section 4.8). To set the real value of a global variable, without invoking any tag method, use lua_rawset over the table of globals
(see below).
All global variables are kept in an ordinary Lua table. You can get this table calling void lua_getglobals (lua_State *L);which pushes the current table of globals onto the stack. To set another table as the table of globals, you call void lua_setglobals (lua_State *L);The table to be used is popped from the stack. 5.10 - Manipulating Tables in LuaLua tables can also be manipulated through the API.To read the value of in a table, the table must reside somewhere in the stack. With this set, you call void lua_gettable (lua_State *L, int index);where index refers to the table.
lua_gettable pops a key from the stack,
and returns (on the stack) the contents of the table at that key.
As in Lua, this operation may trigger a tag method
for the ``gettable'' event.
To get the real value of any table key,
without invoking any tag method,
use the raw version:
void lua_rawget (lua_State *L, int index); To store a value into a table that resides somewhere in the stack, you push the key and the value onto the stack (in this order), and then call void lua_settable (lua_State *L, int index);where index refers to the table.
lua_settable pops from the stack both the key and the value.
As in Lua, this operation may trigger a tag method
for the ``settable'' event.
To set the real value of any table index,
without invoking any tag method,
use the raw version:
void lua_rawset (lua_State *L, int index); void lua_newtable (lua_State *L);creates a new, empty table and pushes it onto the stack. 5.11 - Using Tables as ArraysThe API has functions that help to use Lua tables as arrays, that is, tables indexed by numbers only:void lua_rawgeti (lua_State *L, int index, int n); void lua_rawseti (lua_State *L, int index, int n); int lua_getn (lua_State *L, int index);
5.12 - Calling Lua FunctionsFunctions defined in Lua (and C functions registered in Lua) can be called from the host program. This is done using the following protocol: First, the function to be called is pushed onto the stack; then, the arguments to the function are pushed (see Section 5.5) in direct order, that is, the first argument is pushed first. Finally, the function is called using int lua_call (lua_State *L, int nargs, int nresults);This function returns the same error codes as lua_dostring and
friends (see Section 5.8).
If you want to propagate the error,
instead of returning an error code,
use
void lua_rawcall (lua_State *L, int nargs, int nresults);
In both functions,
The following example shows how the host program may do the equivalent to the Lua code: a,b = f("how", t.x, 4)Here it is in C: lua_getglobal(L, "t"); /* global `t' (for later use) */ lua_getglobal(L, "f"); /* function to be called */ lua_pushstring(L, "how"); /* 1st argument */ lua_pushstring(L, "x"); /* push the string `x' */ lua_gettable(L, -4); /* push result of t.x (2nd arg) */ lua_pushnumber(L, 4); /* 3rd argument */ lua_call(L, 3, 2); /* call function with 3 arguments and 2 results */ lua_setglobal(L, "b"); /* set global variable `b' */ lua_setglobal(L, "a"); /* set global variable `a' */ lua_pop(L, 1); /* remove `t' from the stack */Notice that the code above is ``balanced'': at its end ,the stack is back to its original configuration. This is considered good programming practice.
Some special Lua functions have their own C interfaces. The host program can generate a Lua error calling the function void lua_error (lua_State *L, const char *message);This function never returns. If lua_error is called from a C function that has been called from Lua,
then the corresponding Lua execution terminates,
as if an error had occurred inside Lua code.
Otherwise, the whole host program terminates with a call to
exit(EXIT_FAILURE) .
Before terminating execution,
the message is passed to the error handler function,
_ERRORMESSAGE (see Section 4.7).
If message is NULL ,
then _ERRORMESSAGE is not called.
Tag methods can be changed with void lua_settagmethod (lua_State *L, int tag, const char *event);The second parameter is the tag, and the third is the event name (see Section 4.8); the new method is popped from the stack. To get the current value of a tag method, use the function void lua_gettagmethod (lua_State *L, int tag, const char *event); It is also possible to copy all tag methods from one tag to another: int lua_copytagmethods (lua_State *L, int tagto, int tagfrom);This function returns tagto .
You can traverse a table with the function int lua_next (lua_State *L, int index);where index refers to the table to be traversed.
The function pops a key from the stack,
and pushes a key-value pair from the table
(the ``next'' pair after the given key).
If there are no more elements, then the function returns 0
(and pushes nothing).
A typical traversal looks like this:
/* table is in the stack at index `t' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* `key' is at index -2 and `value' at index -1 */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); lua_pop(L, 1); /* removes `value'; keeps `index' for next iteration */ } void lua_concat (lua_State *L, int n);concatenates the n values at the top of the stack,
pops them, and leaves the result at the top;
n must be at least 2.
Concatenation is done following the usual semantics of Lua
(see Section 4.5.5).
5.13 - Defining C FunctionsTo register a C function to Lua, there is the following convenience macro:#define lua_register(L, n, f) (lua_pushcfunction(L, f), lua_setglobal(L, n)) /* const char *n; */ /* lua_CFunction f; */which receives the name the function will have in Lua, and a pointer to the function. This pointer must have type lua_CFunction ,
which is defined as
typedef int (*lua_CFunction) (lua_State *L);that is, a pointer to a function with integer result and a single argument, a Lua environment. In order to communicate properly with Lua, a C function must follow the following protocol, which defines the way parameters and results are passed: A C function receives its arguments from Lua in the stack, in direct order (the first argument is pushed first). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Like a Lua function, a C function called by Lua can also return many results. As an example, the following function receives a variable number of numerical arguments and returns their average and sum: static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ double sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) lua_error(L, "incorrect argument to function `average'"); sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */ }This function may be registered in Lua as ` average ' by calling
lua_register(L, "average", foo);
When a C function is created, it is possible to associate some upvalues to it (see Section 4.6), thus creating a C closure; these values are passed to the function whenever it is called, as ordinary arguments. To associate upvalues to a C function, first these values should be pushed onto the stack. Then the function void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);is used to push the C function onto the stack, with the argument n telling how many upvalues should be
associated with the function
(these upvalues are popped from the stack);
in fact, the macro lua_pushcfunction is defined as
lua_pushcclosure with n set to 0.
Then, whenever the C function is called,
these upvalues are inserted as the last arguments to the function,
after the actual arguments provided in the call.
This makes it easy to get the upvalues without knowing how many arguments
the function received (recall that functions in Lua can receive any number of
arguments): The i-th upvalue is in the stack at index i-(n+1),
where n is the number of upvalues.
For more examples of C functions and closures, see files
5.14 - References to Lua ObjectsIf the C code needs to keep a Lua value outside the life span of a C function, then it must create a reference to the value. The functions to manipulate references are the following: int lua_ref (lua_State *L, int lock); int lua_getref (lua_State *L, int ref); void lua_unref (lua_State *L, int ref);
Whenever the referenced object is needed in C,
a call to
When a reference is no longer needed,
it should be released with a call to
RegistryWhen Lua starts, it registers a table at position LUA_REFREGISTRY. It can be accessed through the macro #define lua_getregistry(L) lua_getref(L, LUA_REFREGISTRY)This table can be used by C libraries as a general registry mechanism. Any C library can store data into this table, as long as it chooses a key different from other libraries.
6 - Standard LibrariesThe standard libraries provide useful functions that are implemented directly through the standard API. Therefore, they are not necessary to the language, and are provided as separate C modules. Currently, Lua has the following standard libraries:
lua_baselibopen ,
lua_strlibopen , lua_mathlibopen ,
and lua_iolibopen , which are declared in lualib.h .
6.1 - Basic Functions
The basic library provides some core functions to Lua.
Therefore, if you do not include this library in your application,
you should check carefully whether you need to provide some alternative
implementation for some facilities.
(For instance,
without function _ALERT (message)Prints its only string argument to stderr. All error messages in Lua are printed through the function stored in the_ALERT global variable
(see Section 4.7).
Therefore, a program may assign another function to this variable
to change the way such messages are shown
(for instance, for systems without stderr ).
assert (v [, message])Issues an ``assertion failed!'' error when its argumentv is nil.
This function is equivalent to the following Lua function:
function assert (v, m) if not v then m = m or "" error("assertion failed! " .. m) end end
call (func, arg [, mode [, errhandler]])Calls functionfunc with
the arguments given by the table arg .
The call is equivalent to
func(arg[1], arg[2], ..., arg[n])where n is the result of getn(arg) (see Section 6.1).
All results from func are simply returned by call .
By default,
if an error occurs during the call to
If
collectgarbage ([limit])
Sets the garbage-collection threshold for the given limit
(in Kbytes), and checks it against the byte counter.
If the new threshold is smaller than the byte counter,
then Lua immediately runs the garbage collector (see Section 5.6).
If
copytagmethods (tagto, tagfrom)Copies all tag methods from one tag to another; returnstagto .
dofile (filename)Receives a file name, opens the named file, and executes its contents as a Lua chunk, or as pre-compiled chunks. When called without arguments,dofile executes the contents of the standard input (stdin ).
If there is any error executing the file,
then dofile returns nil.
Otherwise, it returns the values returned by the chunk,
or a non-nil value if the chunk returns no values.
It issues an error when called with a non-string argument.
dostring (string [, chunkname])Executes a given string as a Lua chunk. If there is any error executing the string, thendostring returns nil.
Otherwise, it returns the values returned by the chunk,
or a non-nil value if the chunk returns no values.
The optional parameter chunkname
is the ``name of the chunk'',
used in error messages and debug information.
error (message)Calls the error handler (see Section 4.7) and then terminates the last protected function called (in C:lua_dofile , lua_dostring ,
lua_dobuffer , or lua_callfunction ;
in Lua: dofile , dostring , or call in protected mode).
If message is nil, then the error handler is not called.
Function error never returns.
foreach (table, func)Executes the givenfunc over all elements of table .
For each element, the function is called with the index and
respective value as arguments.
If the function returns any non-nil value,
then the loop is broken, and this value is returned
as the final value of foreach .
This function could be defined in Lua:
function foreach (t, f) for i, v in t do local res = f(i, v) if res then return res end end end
The behavior of
foreachi (table, func)Executes the givenfunc over the
numerical indices of table .
For each index, the function is called with the index and
respective value as arguments.
Indices are visited in sequential order,
from 1 to n ,
where n is the result of getn(table) (see Section 6.1).
If the function returns any non-nil value,
then the loop is broken, and this value is returned
as the final value of foreachi .
This function could be defined in Lua:
function foreachi (t, f) for i=1,getn(t) do local res = f(i, t[i]) if res then return res end end end
getglobal (name)Gets the value of a global variable, or calls a tag method for ``getglobal''. Its full semantics is explained in Section 4.8. The stringname does not need to be a
syntactically valid variable name.
getn (table)Returns the ``size'' of a table, when seen as a list. If the table has ann field with a numeric value,
this value is the ``size'' of the table.
Otherwise, the ``size'' is the largest numerical index with a non-nil
value in the table.
This function could be defined in Lua:
function getn (t) if type(t.n) == "number" then return t.n end local max = 0 for i, _ in t do if type(i) == "number" and i>max then max=i end end return max end
gettagmethod (tag, event)Returns the current tag method for a given pair (tag, event). This function cannot be used to get a tag method for the ``gc'' event. (Such tag methods can only be manipulated by C code.)
globals ([table])Returns the current table of globals. If the argumenttable is given,
then it also sets this table as the table of globals.
newtag ()Returns a new tag.
next (table, [index])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.next returns the next index of the table and the
value associated with the index.
When called with nil as its second argument,
next returns the first index
of the table and its associated value.
When called with the last index,
or with nil in an empty table,
next returns nil.
If the second argument is absent, then it is interpreted as nil.
Lua has no declaration of fields;
semantically, there is no difference between a
field not present in a table or a field with value nil.
Therefore,
The behavior of
print (e1, e2, ...)Receives any number of arguments, and prints their values using the strings returned bytostring .
This function is not intended for formatted output,
but only as a quick way to show a value,
for instance for debugging.
See Section 6.4 for functions for formatted output.
rawget (table, index)Gets the real value oftable[index] ,
without invoking any tag method.
table must be a table,
and index is any value different from nil.
rawset (table, index, value)Sets the real value oftable[index] to value ,
without invoking any tag method.
table must be a table,
index is any value different from nil,
and value is any Lua value.
setglobal (name, value)Sets the named global variable to the given value, or calls a tag method for ``setglobal''. Its full semantics is explained in Section 4.8. The stringname does not need to be a
syntactically valid variable name.
settag (t, tag)Sets the tag of a given table (see Section 3).tag must be a value created with newtag
(see Section 6.1).
settag returns the value of its first argument (the table).
For the safety of host programs,
it is impossible to change the tag of a userdata from Lua.
settagmethod (tag, event, newmethod)Sets a new tag method to the given pair (tag, event) and returns the old method. Ifnewmethod is nil,
then settagmethod restores the default behavior for the given event.
This function cannot be used to set a tag method for the ``gc'' event.
(Such tag methods can only be manipulated by C code.)
sort (table [, comp])Sorts table elements in a given order, in-place, fromtable[1] to table[n] ,
where n is the result of getn(table) (see Section 6.1).
If comp is given,
then it must be a function that receives two table elements,
and returns true (that is, a value different from nil)
when the first is less than the second
(so that not comp(a[i+1], a[i]) will be true after the sort).
If comp is not given,
then the standard Lua operator < is used instead.
The sort algorithm is not stable (that is, elements considered equal by the given order may have their relative positions changed by the sort). tag (v)Allows Lua programs to test the tag of a value (see Section 3). It receives one argument, and returns its tag (a number).
tonumber (e [, base])Tries to convert its argument to a number. If the argument is already a number or a string convertible to a number, thentonumber returns that number;
otherwise, it returns nil.
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 `A' (either upper or lower case) represents 10, `B' represents 11, and so forth, with `Z' representing 35. In base 10 (the default), the number may have a decimal part, as well as an optional exponent part (see Section 4.2). In other bases, only unsigned integers are accepted.
tostring (e)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 functionformat .
tinsert (table [, pos] , value)
Inserts element function tinsert (t, ...) local pos, value local n = getn(t) if arg.n == 1 then pos, value = n+1, arg[1] else pos, value = arg[1], arg[2] end t.n = n+1; for i=n,pos,-1 do t[i+1] = t[i] end t[pos] = value end
tremove (table [, pos])
Removes from This function is equivalent to the following Lua function, except that the table accesses are all raw (that is, without tag methods): function tremove (t, pos) local n = getn(t) if n<=0 then return end pos = pos or n local value = t[pos] for i=pos,n-1 do t[i] = t[i+1] end t[n] = nil t.n = n-1 return value end type (v)Allows Lua programs to test the type of a value. It receives one argument, and returns its type, coded as a string. The possible results of this function are"nil" (a string, not the value nil),
"number" ,
"string" ,
"table" ,
"function" ,
and "userdata" .
6.2 - String ManipulationThis 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). Also, indices are allowed to be negative and are intepreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.
strbyte (s [, i])Returns the internal numerical code of the i-th character ofs .
If i is absent, then it is assumed to be 1.
i may be negative.
Numerical codes are not necessarily portable across platforms.
strchar (i1, i2, ...)Receives 0 or more integers. Returns a string with length equal to the number of arguments, wherein each character has the internal numerical code equal to its correspondent argument.Numerical codes are not necessarily portable across platforms.
strfind (s, pattern [, init [, plain]])Looks for the first match ofpattern in s .
If it finds one, then strfind returns the indices of s
where this occurrence starts and ends;
otherwise, it returns nil.
If the pattern specifies captures (see gsub below),
the captured strings are returned as extra results.
A third, optional numerical argument init specifies
where to start the search;
its default value is 1, and may be negative.
A value of 1 as a fourth, optional argument plain
turns off the pattern matching facilities,
so the function does a plain ``find substring'' operation,
with no characters in pattern being considered ``magic''.
Note that if plain is given, then init must be given too.
strlen (s)Receives a string and returns its length. The empty string"" has length 0.
Embedded zeros are counted,
and so "a\000b\000c" has length 5.
strlower (s)Receives a string and returns a copy of that string with all upper case letters changed to lower case. All other characters are left unchanged. The definition of what is an upper-case letter depends on the current locale.
strrep (s, n)Returns a string that is the concatenation ofn copies of
the string s .
strsub (s, i [, j])Returns another string, which is a substring ofs ,
starting at i and running until j ;
i and j may be negative,
If j is absent, then it is assumed to be equal to -1
(which is the same as the string length).
In particular,
the call strsub(s,1,j) returns a prefix of s
with length j ,
and the call strsub(s, -i) returns a suffix of s
with length i .
strupper (s)Receives a string and returns a copy of that string with all lower case letters changed to upper case. All other characters are left unchanged. The definition of what is a lower case letter depends on the current locale.
format (formatstring, e1, e2, ...)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 theprintf family of
standard C functions.
The only differences are that the options/modifiers
* , l , L , n , p ,
and h are not supported,
and there is an extra option, q .
The q 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, returns, and backslashes in the string
are correctly escaped when written.
For instance, the call
format('%q', 'a string with "quotes" and \n new line')will produce the string: "a string with \"quotes\" and \ new line"
Conversions can be applied to the n-th argument in the argument list,
rather than the next unused argument.
In this case, the conversion character
The options
Neither the format string nor the string values to be formatted with
gsub (s, pat, repl [, n])Returns a copy ofs
in which all occurrences of the pattern pat have been
replaced by a replacement string specified by repl .
gsub also returns, as a second value,
the total number of substitutions made.
If
If
The last, optional parameter Here are some examples: x = gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world"
Patterns
Character Class:a character class is used to represent a set of characters. The following combinations are allowed in describing a character class:
%a , %c , ...),
the corresponding upper-case letter represents the complement of the class.
For instance, %S represents all non-space characters.
The definitions of letter, space, etc. depend on the current locale.
In particular, the class
Pattern Item:a pattern item may be
Pattern:a pattern is a sequence of pattern items. A^ at the beginning of a pattern anchors the match at the
beginning of the subject string.
A $ at the end of a pattern anchors the match at the
end of the subject string.
At other positions,
^ and $ have no special meaning and represent themselves.
Captures:A pattern may contain sub-patterns enclosed in parentheses, they describe captures. When a match succeeds, the sub-strings of the subject string that match captures are stored (captured) for future use. Captures are numbered according to their left parentheses. For instance, in the pattern"(a*(.)%w(%s*))" ,
the part of the string matching "a*(.)%w(%s*)" is
stored as the first capture (and therefore has number 1);
the character matching . is captured with number 2,
and the part matching %s* has number 3.
A pattern cannot contain embedded zeros. Use
6.3 - Mathematical Functions
This library is an interface to some functions of the standard C math library.
In addition, it registers a tag method for the binary operator The library provides the following functions: abs acos asin atan atan2 ceil cos deg exp floor log log10 max min mod rad sin sqrt tan frexp ldexp random randomseedplus a global variable PI. Most of them are only interfaces to the homonymous functions in the C library, except that, for the trigonometric functions, all angles are expressed in degrees, not radians. The functions deg and rad can be used to convert
between radians and degrees.
The function
The functions
6.4 - I/O Facilities
All input and output operations in Lua are done, by default,
over two file handles, one for reading and one for writing.
These handles are stored in two Lua global variables,
called
A file handle is a userdata containing the file stream ( Unless otherwise stated, all I/O functions return nil on failure and some value different from nil on success.
openfile (filename, mode)
This function opens a file,
in the mode specified in the string
The
mode string may also have a b at the end,
which is needed in some systems to open the file in binary mode.
This string is exactlty what is used in the standard C function fopen .
closefile (handle)
This function closes the given file.
It does not modify either
readfrom (filename)
This function may be called in two ways.
When called with a file name, it opens the named file,
sets its handle as the value of
If
writeto (filename)
This function may be called in two ways.
When called with a file name,
it opens the named file,
sets its handle as the value of
If
appendto (filename)
Opens a file named
remove (filename)Deletes the file with the given name. If this function fails, it returns nil, plus a string describing the error.
rename (name1, name2)
Renames file named
flush ([filehandle])
Saves any written data to the given file.
If
seek (filehandle [, whence] [, offset])
Sets and gets the file position,
measured in bytes from the beginning of the file,
to the position given by
seek returns the final file position,
measured in bytes from the beginning of the file.
If the call fails, it returns nil,
plus a string describing the error.
The default value for
tmpname ()Returns a string with a file name that can safely be used for a temporary file. The file must be explicitly opened before its use and removed when no longer needed.
read ([filehandle,] format1, ...)
Reads file The available formats are
write ([filehandle, ] value1, ...)
Writes the value of each of its arguments to
file 6.5 - System Facilities
clock ()Returns an approximation of the amount of CPU time used by the program, in seconds.
date ([format])
Returns a string containing date and time
formatted according to the given string
execute (command)
This function is equivalent to the C function
exit ([code])
Calls the C function
getenv (varname)
Returns the value of the process environment variable
setlocale (locale [, category])
This function is an interface to the ANSI C function
7 - The Debug Interface
Lua has no built-in debugging facilities.
Instead, it offers a special interface,
by means of functions and hooks,
which allows the construction of different
kinds of debuggers, profilers, and other tools
that need ``inside information'' from the interpreter.
This interface is declared in 7.1 - Stack and Function InformationThe main function to get information about the interpreter stack is int lua_getstack (lua_State *L, int level, lua_Debug *ar);It fills parts of a lua_Debug structure with
an identification of the activation record
of the function executing at a given level.
Level 0 is the current running function,
whereas level n+1 is the function that has called level n.
Usually, lua_getstack returns 1;
when called with a level greater than the stack depth,
it returns 0.
The structure typedef struct lua_Debug { const char *event; /* "call", "return" */ int currentline; /* (l) */ const char *name; /* (n) */ const char *namewhat; /* (n) global, tag method, local, field */ int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ const char *what; /* (S) "Lua" function, "C" function, Lua "main" */ const char *source; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ lua_getstack fills only the private part
of this structure, for future use.
To fill in the other fields of lua_Debug with useful information,
call
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);This function returns 0 on error (e.g., an invalid option in what ).
Each character in the string what
selects some fields of ar to be filled,
as indicated by the letter in parentheses in the definition of lua_Debug :
`S ' fills in the fields source , linedefined ,
and what ;
`l ' fills in the field currentline , etc.
Moreover, `f ' pushes onto the stack the function that is
running at the given level.
To get information about a function that is not active (that is,
it is not in the stack),
you push the function onto the stack,
and start the lua_Debug ar; lua_getglobal(L, "f"); lua_getinfo(L, ">S", &ar); printf("%d\n", ar.linedefined);The fields of lua_Debug have the following meaning:
7.2 - Manipulating Local Variables
For the manipulation of local variables,
The following functions allow the manipulation of the local variables of a given activation record. const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);The parameter ar must be a valid activation record,
filled by a previous call to lua_getstack or
given as argument to a hook (see Section 7.3).
Function lua_getlocal gets the index of a local variable
(n ), pushes its value onto the stack,
and returns its name.
For lua_setlocal ,
you push the new value onto the stack,
and the function assigns that value to the variable and returns its name.
Both functions return NULL on failure;
that happens if the index is greater than
the number of active local variables.
As an example, the following function lists the names of all local variables for a function at a given level of the stack: int listvars (lua_State *L, int level) { lua_Debug ar; int i = 1; const char *name; if (lua_getstack(L, level, &ar) == 0) return 0; /* failure: no such level in the stack */ while ((name = lua_getlocal(L, &ar, i++)) != NULL) { printf("%s\n", name); lua_pop(L, 1); /* remove variable value */ } return 1; }
7.3 - HooksThe Lua interpreter offers two hooks for debugging purposes: a call hook and a line hook. Both have the same type, typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);and you can set them with the following functions: lua_Hook lua_setcallhook (lua_State *L, lua_Hook func); lua_Hook lua_setlinehook (lua_State *L, lua_Hook func);A hook is disabled when its value is NULL ,
which is the initial value of both hooks.
The functions lua_setcallhook and lua_setlinehook
set their corresponding hooks and return their previous values.
The call hook is called whenever the
interpreter enters or leaves a function.
The
The line hook is called every time the interpreter changes
the line of code it is executing.
The While Lua is running a hook, it disables other calls to hooks. Therefore, if a hook calls Lua to execute a function or a chunk, this execution ocurrs without any calls to hooks.
7.4 - The Reflexive Debug Interface
The library You should exert great care when using this library. The functions provided here should be used exclusively for debugging and similar tasks (e.g., profiling). Please resist the temptation to use them as a usual programming tool. They are slow and violate some (otherwise) secure aspects of the language (e.g., privacy of local variables). As a general rule, if your program does not need this library, do not open it.
getinfo (function, [what])
This function returns a table with information about a function.
You can give the function directly,
or you can give a number as the value of
The returned table contains all the fields returned by
For instance, the expression
getlocal (level, local)
This function returns the name and the value of the local variable
with index
setlocal (level, local, value)
This function assigns the value
setcallhook (hook)
Sets the function
setlinehook (hook)
Sets the function
8 - Lua Stand-alone
Although Lua has been designed as an extension language,
to be embedded in a host C program,
it is frequently used as a stand-alone language.
An interpreter for Lua as a stand-alone language,
called simply
lua behaves as lua -v -i when stdin is a terminal,
and as lua - otherwise.
All arguments are handled in order, except $ lua -i a=test prog.luawill first interact with the user until an EOF in stdin ,
then will set a to "test" ,
and finally will run the file prog.lua .
(Here,
$ is the shell prompt. Your prompt may be different.)
When the option -f filename is used,
all remaining arguments in the command line
are passed to the Lua program $ lua a.lua -f b.lua t1 t3the interpreter first runs the file a.lua, then creates a table arg = {"t1", "t3"; n = 2, [0] = "b.lua"}and finally runs the file b.lua. The stand-alone interpreter also provides a getargs function that
can be used to access all command line arguments.
For instance, if you call Lua with the line
$ lua -c a bthen a call to getargs in a or b will return the table
{[0] = "lua", [1] = "-c", [2] = "a", [3] = "b", n = 3}
In interactive mode,
a multi-line statement can be written finishing intermediate
lines with a backslash (` $ lua _PROMPT='myprompt> ' -ior in any Lua programs by assigning to _PROMPT .
In Unix systems, Lua scripts can be made into executable programs
by using
AcknowledgmentsThe authors would like to thank CENPES/PETROBRAS which, jointly with TeCGraf, used early versions of this system extensively and gave valuable comments. The authors would also like to thank Carlos Henrique Levy, who found the name of the game. Lua means ``moon'' in Portuguese.
Incompatibilities with Previous VersionsLua 4.0 is a major revision of the language. We took a great care to avoid incompatibilities with the previous public versions of Lua, but some differences had to be introduced. Here is a list of all these incompatibilities.
Incompatibilities with version 3.2
Changes in the Language
Changes in the Libraries
Changes in the API
The Complete Syntax of Lua
Last update: Mon Nov 6 17:37:03 EDT 2000 by lhf. |