people use body languagr to send messages logging的翻泽

Lua is a powerful, efficient, lightweight, embeddable scripting language.
It supports procedural programming,
object-oriented programming, functional programming,
data-driven programming, and data description.
Lua combines simple procedural syntax with powerful data description
constructs based on associative arrays and extensible semantics.
Lua is dynamically typed,
runs by interpreting bytecode with a register-based
virtual machine,
and has automatic memory management with
incremental garbage collection,
making it ideal for configuration, scripting,
and rapid prototyping.
Lua is implemented as a library, written in clean C,
the common subset of Standard&C and C++.
The Lua distribution includes a host program called lua,
which uses the Lua library to offer a complete,
standalone Lua interpreter,
for interactive or batch use.
Lua is intended to be used both as a powerful, lightweight,
embeddable scripting language for any program that needs one,
and as a powerful but lightweight and efficient stand-alone language.
As an extension language, Lua has no notion of a "main" program:
it works embedded in a host client,
called the embedding program or simply the host.
(Frequently, this host is the stand-alone lua program.)
The host program can invoke 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.
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 software,
and is provided as usual with no guarantees,
as stated in its license.
The implementation described in this manual is available
at Lua's official web site, www.lua.org.
Like any other reference manual,
this document is dry in places.
For a discussion of the decisions behind the design of Lua,
see the technical papers available at Lua's web site.
For a detailed introduction to programming in Lua,
see Roberto's book, Programming in Lua.
This section describes the basic concepts of the language.
Lua is a dynamically typed language.
This means that
variabl only values do.
There are no type definitions in the language.
All values carry their own type.
All values in Lua are first-class values.
This means that all values can be stored in variables,
passed as arguments to other functions, and returned as results.
There are eight basic types in Lua:
nil, boolean, number,
string, function, userdata,
thread, and table.
The type nil has one single value, nil,
whose main property is to be different
it usually represents the absence of a useful value.
The type boolean has two values, false and true.
Both nil and false ma
any other value makes it true.
The type number represents both
integer numbers and real (floating-point) numbers.
The type string represents immutable sequences of bytes.
Lua is 8-bit clean:
strings can contain any 8-bit value,
including embedded zeros ('\0').
Lua is also encoding-
it makes no assumptions about the contents of a string.
The type number uses two internal representations,
or two subtypes,
one called integer and the other called float.
Lua has explicit rules about when each representation is used,
but it also converts between them automatically as needed (see ).
Therefore,
the programmer may choose to mostly ignore the difference
between integers and floats
or to assume complete control over the representation of each number.
Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
but you can also compile Lua so that it
uses 32-bit integers and/or single-precision (32-bit) floats.
The option with 32 bits for both integers and floats
is particularly attractive
for small machines and embedded systems.
(See macro LUA_32BITS in file luaconf.h.)
Lua can call (and manipulate) functions written in Lua and
functions written in C (see ).
Both are represented by the type function.
The type userdata is provided to allow arbitrary C&data to
be stored in Lua variables.
A userdata value represents a block of raw memory.
There are two kinds of userdata:
full userdata,
which is an object with a block of memory managed by Lua,
and light userdata,
which is simply a C&pointer value.
Userdata has no predefined operations in Lua,
except assignment and identity test.
By using metatables,
the programmer can define operations for full userdata values
Userdata values cannot be created or modified in Lua,
only through the C&API.
This guarantees the integrity of data owned by the host program.
The type thread represents independent threads of execution
and it is used to implement coroutines (see ).
Lua threads are not related to operating-system threads.
Lua supports coroutines on all systems,
even those that do not support threads natively.
The type table implements associative arrays,
that is, arrays that can be indexed not only with numbers,
but with any Lua value except nil and NaN.
(Not a Number is a special value used to represent
undefined or unrepresentable numerical results, such as 0/0.)
Tables can be heterogeneous;
that is, they can contain values of all types (except nil).
Any key with value nil is not considered part of the table.
Conversely, any key that is not part of a table has
an associated value nil.
Tables are the sole data-structuring mechanism in L
they can be used to represent ordinary arrays, lists,
symbol tables, sets, records, graphs, trees, etc.
To represent records, Lua uses the field name as an index.
The language supports this representation by
providing a.name as syntactic sugar for a["name"].
There are several convenient ways to create tables in Lua
Like indices,
the values of table fields can be of any type.
In particular,
because functions are first-class values,
table fields can contain functions.
Thus tables can also carry methods (see ).
The indexing of tables follows
the definition of raw equality in the language.
The expressions a[i] and a[j]
denote the same table element
if and only if i and j are raw equal
(that is, equal without metamethods).
In particular, floats with integral values
are equal to their respective integers
(e.g., 1.0 == 1).
To avoid ambiguities,
any float with integral value used as a key
is converted to its respective integer.
For instance, if you write a[2.0] = true,
the actual key inserted into the table will be the
integer 2.
(On the other hand,
2 and "2" are different Lua values and therefore
denote different table entries.)
Tables, functions, threads, and (full) userdata values are objects:
variables do not actually contain these values,
only references to them.
Assignment, parameter passing, and function returns
always manipulate refer
these operations do not imply any kind of copy.
The library function
returns a string describing the type
of a given value (see ).
As will be discussed in
any reference to a free name
(that is, a name not bound to any declaration) var
is syntactically translated to _ENV.var.
Moreover, every chunk is compiled in the scope of
an external local variable named _ENV (see ),
so _ENV itself is never a free name in a chunk.
Despite the existence of this external _ENV variable and
the translation of free names,
_ENV is a completely regular name.
In particular,
you can define new variables and parameters with that name.
Each reference to a free name uses the _ENV that is
visible at that point in the program,
following the usual visibility rules of Lua (see ).
Any table used as the value of _ENV is called an environment.
Lua keeps a distinguished environment called the global environment.
This value is kept at a special index in the C registry (see ).
In Lua, the global variable
is initialized with this same value.
( is never used internally.)
When Lua loads a chunk,
the default value for its _ENV upvalue
is the global environment (see ).
Therefore, by default,
free names in Lua code refer to entries in the global environment
(and, therefore, they are also called global variables).
Moreover, all standard libraries are loaded in the global environment
and some functions there operate on that environment.
You can use
to load a chunk with a different environment.
(In C, you have to load the chunk and then change the value
of its first upvalue.)
Because Lua is an embedded extension language,
all Lua actions start from C&code in the host program
calling a function from the Lua library.
(When you use Lua standalone,
the lua application is the host program.)
Whenever an error occurs during
the compilation or execution of a Lua chunk,
control returns to the host,
which can take appropriate measures
(such as printing an error message).
Lua code can explicitly generate an error by calling the
If you need to catch errors in Lua,
you can use
to call a given function in protected mode.
Whenever there is an error,
an error object (also called an error message)
is propagated with information about the error.
Lua itself only generates errors whose error object is a string,
but programs may generate errors with
any value as the error object.
It is up to the Lua program or its host to handle such error objects.
When you use
you may give a message handler
to be called in case of errors.
This function is called with the original error object
and returns a new error object.
It is called before the error unwinds the stack,
so that it can gather more information about the error,
for instance by inspecting the stack and creating a stack traceback.
This message handler is still protected b
so, an error inside the message handler
will call the message handler again.
If this loop goes on for too long,
Lua breaks it and returns an appropriate message.
(The message handler is called only for regular runtime errors.
It is not called for memory-allocation errors
nor for errors while running finalizers.)
Every value in Lua can have a metatable.
This metatable is an ordinary Lua table
that defines the behavior of the original value
under certain special operations.
You can change several aspects of the behavior
of operations over a value by setting specific fields in its metatable.
For instance, when a non-numeric value is the operand of an addition,
Lua checks for a function in the field "__add" of the value's metatable.
If it finds one,
Lua calls this function to perform the addition.
The key for each event in a metatable is a string
with the event name prefixe
the corresponding values are called metamethods.
In the previous example, the key is "__add"
and the metamethod is the function that performs the addition.
You can query the metatable of any value
Lua queries metamethods in metatables using a raw access (see ).
So, to retrieve the metamethod for event ev in object o,
Lua does the equivalent to the following code:
rawget(getmetatable(o) or {}, "__ev")
You can replace the metatable of tables
You cannot change the metatable of other types from Lua code
(except by using the debug library ());
you should use the C&API for that.
Tables and full userdata have individual metatables
(although multiple tables and userdata can share their metatables).
Values of all other types share one singl
that is, there is one single metatable for all numbers,
one for all strings, etc.
By default, a value has no metatable,
but the string library sets a metatable for the string type (see ).
A metatable controls how an object behaves in
arithmetic operations, bitwise operations,
order comparisons, concatenation, length operation, calls, and indexing.
A metatable also can define a function to be called
when a userdata or a table is garbage collected ().
For the unary operators (negation, length, and bitwise NOT),
the metamethod is computed and called with a dummy second operand,
equal to the first one.
This extra operand is only to simplify Lua's internals
(by making these operators behave like a binary operation)
and may be removed in future versions.
(For most uses this extra operand is irrelevant.)
A detailed list of events controlled by metatables is given next.
Each operation is identified by its corresponding key.
the addition (+) operation.
If any operand for an addition is not a number
(nor a string coercible to a number),
Lua will try to call a metamethod.
First, Lua will check the first operand (even if it is valid).
If that operand does not define a metamethod for __add,
then Lua will check the second operand.
If Lua can find a metamethod,
it calls the metamethod with the two operands as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
Otherwise,
it raises an error.
the subtraction (-) operation.
Behavior similar to the addition operation.
the multiplication (*) operation.
Behavior similar to the addition operation.
the division (/) operation.
Behavior similar to the addition operation.
the modulo (%) operation.
Behavior similar to the addition operation.
the exponentiation (^) operation.
Behavior similar to the addition operation.
the negation (unary -) operation.
Behavior similar to the addition operation.
the floor division (//) operation.
Behavior similar to the addition operation.
the bitwise AND (&) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod
if any operand is neither an integer
nor a value coercible to an integer (see ).
the bitwise OR (|) operation.
Behavior similar to the bitwise AND operation.
the bitwise exclusive OR (binary ~) operation.
Behavior similar to the bitwise AND operation.
the bitwise NOT (unary ~) operation.
Behavior similar to the bitwise AND operation.
the bitwise left shift (&&) operation.
Behavior similar to the bitwise AND operation.
the bitwise right shift (&&) operation.
Behavior similar to the bitwise AND operation.
the concatenation (..) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod
if any operand is neither a string nor a number
(which is always coercible to a string).
the length (#) operation.
If the object is not a string,
Lua will try its metamethod.
If there is a metamethod,
Lua calls it with the object as argument,
and the result of the call
(always adjusted to one value)
is the result of the operation.
If there is no metamethod but the object is a table,
then Lua uses the table length operation (see ).
Otherwise, Lua raises an error.
the equal (==) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod only when the values
being compared are either both tables or both full userdata
and they are not primitively equal.
The result of the call is always converted to a boolean.
the less than (&) operation.
Behavior similar to the addition operation,
except that Lua will try a metamethod only when the values
being compared are neither both numbers nor both strings.
The result of the call is always converted to a boolean.
the less equal (&=) operation.
Unlike other operations,
the less-equal operation can use two different events.
First, Lua looks for the __le metamethod in both operands,
like in the less than operation.
If it cannot find such a metamethod,
then it will try the __lt metamethod,
assuming that a &= b is equivalent to not (b & a).
As with the other comparison operators,
the result is always a boolean.
(This use of the __lt event can be remove
it is also slower than a real __le metamethod.)
The indexing access table[key].
This event happens when table is not a table or
when key is not present in table.
The metamethod is looked up in table.
Despite the name,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with table and key as arguments,
and the result of the call
(adjusted to one value)
is the result of the operation.
If it is a table,
the final result is the result of indexing this table with key.
(This indexing is regular, not raw,
and therefore can trigger another metamethod.)
__newindex:
The indexing assignment table[key] = value.
Like the index event,
this event happens when table is not a table or
when key is not present in table.
The metamethod is looked up in table.
Like with indexing,
the metamethod for this event can be either a function or a table.
If it is a function,
it is called with table, key, and value as arguments.
If it is a table,
Lua does an indexing assignment to this table with the same key and value.
(This assignment is regular, not raw,
and therefore can trigger another metamethod.)
Whenever there is a __newindex metamethod,
Lua does not perform the primitive assignment.
(If necessary,
the metamethod itself can call
to do the assignment.)
The call operation func(args).
This event happens when Lua tries to call a non-function value
(that is, func is not a function).
The metamethod is looked up in func.
If present,
the metamethod is called with func as its first argument,
followed by the arguments of the original call (args).
All results of the call
are the result of the operation.
(This is the only metamethod that allows multiple results.)
It is a good practice to add all needed metamethods to a table
before setting it as a metatable of some object.
In particular, the __gc metamethod works only when this order
is followed (see ).
Because metatables are regular tables,
they can contain arbitrary fields,
not only the event names defined above.
Some functions in the standard library
use other fields in metatables for their own purposes.
Lua performs automatic memory management.
This means that
you do not have to worry about allocating memory for new objects
or freeing it when the objects are no longer needed.
Lua manages memory automatically by running
a garbage collector to collect all dead objects
(that is, objects that are no longer accessible from Lua).
All memory used by Lua is subject to automatic management:
strings, tables, userdata, functions, threads, internal structures, etc.
Lua implements an incremental mark-and-sweep collector.
It uses two numbers to control its garbage-collection cycles:
the garbage-collector pause and
the garbage-collector step multiplier.
Both use percentage points as units
(e.g., a value of 100 means an internal value of 1).
The garbage-collector pause
controls how long the collector waits before starting a new cycle.
Larger values make the collector less aggressive.
Values smaller than 100 mean the collector will not wait to
start a new cycle.
A value of 200 means that the collector waits for the total memory in use
to double before starting a new cycle.
The garbage-collector step multiplier
controls the relative speed of the collector relative to
memory allocation.
Larger values make the collector more aggressive but also increase
the size of each incremental step.
You should not use values smaller than 100,
because they make the collector too slow and
can result in the collector never finishing a cycle.
The default is 200,
which means that the collector runs at "twice"
the speed of memory allocation.
If you set the step multiplier to a very large number
(larger than 10% of the maximum number of
bytes that the program may use),
the collector behaves like a stop-the-world collector.
If you then set the pause to 200,
the collector behaves as in old Lua versions,
doing a complete collection every time Lua doubles its
memory usage.
You can change these numbers by calling
You can also use these functions to control
the collector directly (e.g., stop and restart it).
You can set garbage-collector metamethods for tables
and, using the C&API,
for full userdata (see ).
These metamethods are also called finalizers.
Finalizers allow you to coordinate Lua's garbage collection
with external resource management
(such as closing files, network or database connections,
or freeing your own memory).
For an object (table or userdata) to be finalized when collected,
you must mark it for finalization.
You mark an object for finalization when you set its metatable
and the metatable has a field indexed by the string "__gc".
Note that if you set a metatable without a __gc field
and later create that field in the metatable,
the object will not be marked for finalization.
When a marked object becomes garbage,
it is not collected immediately by the garbage collector.
Instead, Lua puts it in a list.
After the collection,
Lua goes through that list.
For each object in the list,
it checks the object's __gc metamethod:
If it is a function,
Lua calls it with the object as
if the metamethod is not a function,
Lua simply ignores it.
At the end of each garbage-collection cycle,
the finalizers for objects are called in
the reverse order that the objects were marked for finalization,
among those col
that is, the first finalizer to be called is the one associated
with the object marked last in the program.
The execution of each finalizer may occur at any point during
the execution of the regular code.
Because the object being collected must still be used by the finalizer,
that object (and other objects accessible only through it)
must be resurrected by Lua.
Usually, this resurrection is transient,
and the object memory is freed in the next garbage-collection cycle.
However, if the finalizer stores the object in some global place
(e.g., a global variable),
then the resurrection is permanent.
Moreover, if the finalizer marks a finalizing object for finalization again,
its finalizer will be called again in the next cycle where the
object is unreachable.
In any case,
the object memory is freed only in a GC cycle where
the object is unreachable and not marked for finalization.
When you close a state (see ),
Lua calls the finalizers of all objects marked for finalization,
following the reverse order that they were marked.
If any finalizer marks objects for collection during that phase,
these marks have no effect.
A weak table is a table whose elements are
weak references.
A weak reference is ignored by the garbage collector.
In other words,
if the only references to an object are weak references,
then the garbage collector will collect that object.
A weak table can have weak keys, weak values, or both.
A table with weak values allows the collection of its values,
but prevents the collection of its keys.
A table with both weak keys and weak values allows the collection of
both keys and values.
In any case, if either the key or the value is collected,
the whole pair is removed from the table.
The weakness of a table is controlled by the
__mode field of its metatable.
If the __mode field is a string containing the character&'k',
the keys in the table are weak.
If __mode contains 'v',
the values in the table are weak.
A table with weak keys and strong values
is also called an ephemeron table.
In an ephemeron table,
a value is considered reachable only if its key is reachable.
In particular,
if the only reference to a key comes through its value,
the pair is removed.
Any change in the weakness of a table may take effect only
at the next collect cycle.
In particular, if you change the weakness to a stronger mode,
Lua may still collect some items from that table
before the change takes effect.
Only objects that have an explicit construction
are removed from weak tables.
Values, such as numbers and light C&functions,
are not subject to garbage collection,
and therefore are not removed from weak tables
(unless their associated values are collected).
Although strings are subject to garbage collection,
they do not have an explicit construction,
and therefore are not removed from weak tables.
Resurrected objects
(that is, objects being finalized
and objects accessible only through objects being finalized)
have a special behavior in weak tables.
They are removed from weak values before running their finalizers,
but are removed from weak keys only in the next collection
after running their finalizers, when such objects are actually freed.
This behavior allows the finalizer to access properties
associated with the object through weak tables.
If a weak table is among the resurrected objects in a collection cycle,
it may not be properly cleared until the next cycle.
Lua supports coroutines,
also called collaborative multithreading.
A coroutine in Lua represents an independent thread of execution.
Unlike threads in multithread systems, however,
a coroutine only suspends its execution by explicitly calling
a yield function.
You create a coroutine by calling .
Its sole argument is a function
that is the main function of the coroutine.
The create function only creates a new coroutine and
returns a handle to it (an object of type thread);
it does not start the coroutine.
You execute a coroutine by calling .
When you first call ,
passing as its first argument
a thread returned by ,
the coroutine starts its execution by
calling its main function.
Extra arguments passed to
are passed
as arguments to that function.
After the coroutine starts running,
it runs until it terminates or yields.
A coroutine can terminate its execution in two ways:
normally, when its main function returns
(explicitly or implicitly, after the last instruction);
and abnormally, if there is an unprotected error.
In case of normal termination,
returns true,
plus any values returned by the coroutine main function.
In case of errors,
returns false
plus an error object.
A coroutine yields by calling .
When a coroutine yields,
the corresponding
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,
also returns true,
plus any values passed to .
The next time you resume the same coroutine,
it continues its execution from the point where it yielded,
with the call to
returning any extra
arguments passed to .
function also creates a coroutine,
but instead of returning the coroutine itself,
it returns a function that, when called, resumes the coroutine.
Any arguments passed to this function
go as extra arguments to .
returns all the values returned by ,
except the first one (the boolean error code).
any error is propagated to the caller.
As an example of how coroutines work,
consider the following code:
function foo (a)
print("foo", a)
return coroutine.yield(2*a)
co = coroutine.create(function (a,b)
print("co-body", a, b)
local r = foo(a+1)
print("co-body", r)
local r, s = coroutine.yield(a+b, a-b)
print("co-body", r, s)
return b, "end"
print("main", coroutine.resume(co, 1, 10))
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))
When you run it, it produces the following output:
cannot resume dead coroutine
You can also create and manipulate coroutines through the C API:
see functions , ,
This section describes the lexis, the syntax, and the semantics of Lua.
In other words,
this section describes
which tokens are valid,
how they can be combined,
and what their combinations mean.
Language constructs will be explained using the usual extended BNF notation,
{a}&means&0 or more a's, and
[a]&means an optional a.
Non-terminals are shown like non-terminal,
keywords are shown like kword,
and other terminal symbols are shown like &=&.
The complete syntax of Lua can be found in
at the end of this manual.
Lua is a free-form language.
It ignores spaces (including new lines) and comments
between lexical elements (tokens),
except as delimiters between names and keywords.
(also called identifiers)
in Lua can be any string of letters,
digits, and underscores,
not beginning with a digit and
not being a reserved word.
Identifiers are used to name variables, table fields, and labels.
The following keywords are reserved
and cannot be used as names:
Lua is a case-sensitive language:
and is a reserved word, but And and AND
are two different, valid names.
As a convention,
programs should avoid creating
names that start with an underscore followed by
one or more uppercase letters (such as ).
The following strings denote other tokens:
A short literal string
can be delimited by matching single or double quotes,
and can contain the following C-like escape sequences:
'\a' (bell),
'\b' (backspace),
'\f' (form feed),
'\n' (newline),
'\r' (carriage return),
'\t' (horizontal tab),
'\v' (vertical tab),
'\\' (backslash),
'\"' (quotation mark [double quote]),
and '\'' (apostrophe [single quote]).
A backslash followed by a line break
results in a newline in the string.
The escape sequence '\z' skips the following span
of white-space characters,
it is particularly useful to break and indent a long literal string
into multiple lines without adding the newlines and spaces
into the string contents.
A short literal string cannot contain unescaped line breaks
nor escapes not forming a valid escape sequence.
We can specify any byte in a short literal string by its numeric value
(including embedded zeros).
This can be done
with the escape sequence \xXX,
where XX is a sequence of exactly two hexadecimal digits,
or with the escape sequence \ddd,
where ddd is a sequence of up to three decimal digits.
(Note that if a decimal escape sequence is to be followed by a digit,
it must be expressed using exactly three digits.)
The UTF-8 encoding of a Unicode character
can be inserted in a literal string with
the escape sequence \u{XXX}
(note the mandatory enclosing brackets),
where XXX is a sequence of one or more hexadecimal digits
representing the character code point.
Literal strings can also be defined using a long format
enclosed by long brackets.
We define an opening long bracket of level n as an opening
square bracket followed by n equal signs followed by another
opening square bracket.
So, an opening long bracket of level&0 is written as [[,
an opening long bracket of level&1 is written as [=[,
and so on.
A closing long bracket
for instance,
a closing long bracket of level&4 is written as
A long literal starts with an opening long bracket of any level and
ends at the first closing long bracket of the same level.
It can contain any text except a closing bracket of the same level.
Literals in this bracketed form can run for several lines,
do not interpret any escape sequences,
and ignore long brackets of any other level.
Any kind of end-of-line sequence
(carriage return, newline, carriage return followed by newline,
or newline followed by carriage return)
is converted to a simple newline.
For convenience,
when the opening long bracket is immediately followed by a newline,
the newline is not included in the string.
As an example, in a system using ASCII
(in which 'a' is coded as&97,
newline is coded as&10, and '1' is coded as&49),
the five literal strings below denote the same string:
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
Any byte in a literal string not
explicitly affected by the previous rules represents itself.
However, Lua opens files for parsing in text mode,
and the system file functions may have problems with
some control characters.
So, it is safer to represent
non-text data as a quoted literal with
explicit escape sequences for the non-text characters.
A numeric constant (or numeral)
can be written with an optional fractional part
and an optional decimal exponent,
marked by a letter 'e' or 'E'.
Lua also accepts hexadecimal constants,
which start with 0x or 0X.
Hexadecimal constants also accept an optional fractional part
plus an optional binary exponent,
marked by a letter 'p' or 'P'.
A numeric constant with a radix point or an exponent
otherwise,
if its value fits in an integer,
it denotes an integer.
Examples of valid integer constants are
Examples of valid float constants are
A comment starts with a double hyphen (--)
anywhere outside a string.
If the text immediately after -- is not an opening long bracket,
the comment is a short comment,
which runs until the end of the line.
Otherwise, it is a long comment,
which runs until the corresponding closing long bracket.
Long comments are frequently used to disable code temporarily.
Variables are places that store values.
There are three kinds of variables in Lua:
global variables, local variables, and table fields.
A single name can denote a global variable or a local variable
(or a function's formal parameter,
which is a particular kind of local variable):
var ::= Name
Name denotes identifiers, as defined in .
Any variable name is assumed to be global unless explicitly declared
as a local (see ).
Local variables are lexically scoped:
local variables can be freely accessed by functions
defined inside their scope (see ).
Before the first assignment to a variable, its value is nil.
Square brackets are used to index a table:
var ::= prefixexp &[& exp &]&
The meaning of accesses to table fields can be changed via metatables.
An access to an indexed variable t[i] is equivalent to
a call gettable_event(t,i).
for a complete description of the
gettable_event function.
This function is not defined or callable in Lua.
We use it here only for explanatory purposes.)
The syntax var.Name is just syntactic sugar for
var["Name"]:
var ::= prefixexp &.& Name
An access to a global variable x
is equivalent to _ENV.x.
Due to the way that chunks are compiled,
_ENV is never a global name (see ).
Lua supports an almost conventional set of statements,
similar to those in Pascal or C.
This set includes
assignments, control structures, function calls,
and variable declarations.
A block is a list of statements,
which are executed sequentially:
block ::= {stat}
Lua has empty statements
that allow you to separate statements with semicolons,
start a block with a semicolon
or write two semicolons in sequence:
stat ::= &;&
Function calls and assignments
can start with an open parenthesis.
This possibility leads to an ambiguity in Lua's grammar.
Consider the following fragment:
(print or io.write)('done')
The grammar could see it in two ways:
a = b + c(print or io.write)('done')
a = b + (print or io.write)('done')
The current parser always sees such constructions
in the first way,
interpreting the open parenthesis
as the start of the arguments to a call.
To avoid this ambiguity,
it is a good practice to always precede with a semicolon
statements that start with a parenthesis:
(print or io.write)('done')
A block can be explicitly delimited to produce a single statement:
stat ::= do block end
Explicit blocks are useful
to control the scope of variable declarations.
Explicit blocks are also sometimes used to
add a return statement in the middle
of another block (see ).
The unit of compilation of Lua is called a chunk.
Syntactically,
a chunk is simply a block:
chunk ::= block
Lua handles a chunk as the body of an anonymous function
with a variable number of arguments
As such, chunks can define local variables,
receive arguments, and return values.
Moreover, such anonymous function is compiled as in the
scope of an external local variable called _ENV (see ).
The resulting function always has _ENV as its only upvalue,
even if it does not use that variable.
A chunk can be stored in a file or in a string inside the host program.
To execute a chunk,
Lua first loads it,
precompiling the chunk's code into instructions for a virtual machine,
and then Lua executes the compiled code
with an interpreter for the virtual machine.
Chunks can also be precompi
see program luac and function
for details.
Programs in source and compiled forms
Lua automatically detects the file type and acts accordingly (see ).
Lua allows multiple assignments.
Therefore, the syntax for assignment
defines a list of variables on the left side
and a list of expressions on the right side.
The elements in both lists are separated by commas:
stat ::= varlist &=& explist
varlist ::= var {&,& var}
explist ::= exp {&,& exp}
Expressions are discussed in .
Before the assignment,
the list of values is adjusted to the length of
the list of variables.
If there are more values than needed,
the excess values are thrown away.
If there are fewer values than needed,
the list is extended with as many
nil's as needed.
If the list of expressions ends with a function call,
then all values returned by that call enter the list of values,
before the adjustment
(except when the call is enc see ).
The assignment statement first evaluates all its expressions
and only then the assignments are performed.
Thus the code
i, a[i] = i+1, 20
sets a[3] to 20, without affecting a[4]
because the i in a[i] is evaluated (to 3)
before it is assigned&4.
Similarly, the line
x, y = y, x
exchanges the values of x and y,
x, y, z = y, z, x
cyclically permutes the values of x, y, and z.
The meaning of assignments to global variables
and table fields can be changed via metatables.
An assignment to an indexed variable t[i] = val is equivalent to
settable_event(t,i,val).
for a complete description of the
settable_event function.
This function is not defined or callable in Lua.
We use it here only for explanatory purposes.)
An assignment to a global name x = val
is equivalent to the assignment
_ENV.x = val (see ).
The control structures
if, while, and repeat have the usual meaning and
familiar syntax:
stat ::= while exp do block end
stat ::= repeat block until exp
stat ::= if exp then block {elseif exp then block} [else block] end
Lua also has a for statement, in two flavors (see ).
The condition expression of a
control structure can return any value.
Both false and nil are considered false.
All values different from nil and false are considered true
(in particular, the number 0 and the empty string are also true).
In the repeat&until loop,
the inner block does not end at the until keyword,
but only after the condition.
So, the condition can refer to local variables
declared inside the loop block.
The goto statement transfers the program control to a label.
For syntactical reasons,
labels in Lua are considered statements too:
stat ::= goto Name
stat ::= label
label ::= &::& Name &::&
A label is visible in the entire block where it is defined,
inside nested blocks where a label with the same name is defined and
inside nested functions.
A goto may jump to any visible label as long as it does not
enter into the scope of a local variable.
Labels and empty statements are called void statements,
as they perform no actions.
The break statement terminates the execution of a
while, repeat, or for loop,
skipping to the next statement after the loop:
stat ::= break
A break ends the innermost enclosing loop.
The return statement is used to return values
from a function or a chunk
(which is an anonymous function).
Functions can return more than one value,
so the syntax for the return statement is
stat ::= return [explist] [&;&]
The return statement can only be written
as the last statement of a block.
If it is really necessary to return in the middle of a block,
then an explicit inner block can be used,
as in the idiom do return end,
because now return is the last statement in its (inner) block.
The for statement has two forms:
one numerical and one generic.
The numerical for loop repeats a block of code while a
control variable runs through an arithmetic progression.
It has the following syntax:
stat ::= for Name &=& exp &,& exp [&,& exp] do block end
The block is repeated for name starting at the value of
the first exp, until it passes the second exp by steps of the
third exp.
More precisely, a for statement like
for v = e1, e2, e3 do block end
is equivalent to the code:
local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
if not (var and limit and step) then error() end
var = var - step
while true do
var = var + step
if (step &= 0 and var & limit) or (step & 0 and var & limit) then
local v = var
Note the following:
All three control expressions are evaluated only once,
before the loop starts.
They must all result in numbers.
var, limit, and step are invisible variables.
The names shown here are for explanatory purposes only.
If the third expression (the step) is absent,
then a step of&1 is used.
You can use break and goto to exit a for loop.
The loop variable v is local to the loop body.
If you need its value after the loop,
assign it to another variable before exiting the loop.
The generic for statement works over functions,
called iterators.
On each iteration, the iterator function is called to produce a new value,
stopping when this new value is nil.
The generic for loop has the following syntax:
stat ::= for namelist in explist do block end
namelist ::= Name {&,& Name}
A for statement like
for var_1, &&&, var_n in explist do block end
is equivalent to the code:
local f, s, var = explist
while true do
local var_1, &&&, var_n = f(s, var)
if var_1 == nil then break end
var = var_1
Note the following:
explist is evaluated only once.
Its results are an iterator function,
and an initial value for the first iterator variable.
f, s, and var are invisible variables.
The names are here for explanatory purposes only.
You can use break to exit a for loop.
The loop variables var_i a
you cannot use their values after the for ends.
If you need these values,
then assign them to other variables before breaking or exiting the loop.
To allow possible side-effects,
function calls can be executed as statements:
stat ::= functioncall
In this case, all returned values are thrown away.
Function calls are explained in .
Local variables can be declared anywhere inside a block.
The declaration can include an initial assignment:
stat ::= local namelist [&=& explist]
If present, an initial assignment has the same semantics
of a multiple assignment (see ).
Otherwise, all variables are initialized with nil.
A chunk is also a block (see ),
and so local variables can be declared in a chunk outside any explicit block.
The visibility rules for local variables are explained in .
The basic expressions in Lua are the following:
exp ::= prefixexp
exp ::= nil | false | true
exp ::= Numeral
exp ::= LiteralString
exp ::= functiondef
exp ::= tableconstructor
exp ::= &...&
exp ::= exp binop exp
exp ::= unop exp
prefixexp ::= var | functioncall | &(& exp &)&
Numerals and literal strin
function definitio
function cal
table constructors are explained in .
Vararg expressions,
denoted by three dots ('...'), can only be used when
directly insi
they are explained in .
Binary operators comprise arithmetic operators (see ),
bitwise operators (see ),
relational operators (see ), logical operators (see ),
and the concatenation operator (see ).
Unary operators comprise the unary minus (see ),
the unary bitwise NOT (see ),
the unary logical not (see ),
and the unary length operator (see ).
Both function calls and vararg expressions can result in multiple values.
If a function call is used as a statement (see ),
then its return list is adjusted to zero elements,
thus discarding all returned values.
If an expression is used as the last (or the only) element
of a list of expressions,
then no adjustment is made
(unless the expression is enclosed in parentheses).
In all other contexts,
Lua adjusts the result list to one element,
either discarding all values except the first one
or adding a single nil if there are no values.
Here are some examples:
-- adjusted to 0 results
-- f() is adjusted to 1 result
-- g gets x plus all results from f()
a,b,c = f(), x
-- f() is adjusted to 1 result (c gets nil)
-- a gets the first vararg parameter, b gets
-- the second (both a and b can get nil if there
-- is no corresponding vararg parameter)
a,b,c = x, f()
-- f() is adjusted to 2 results
a,b,c = f()
-- f() is adjusted to 3 results
return f()
-- returns all results from f()
return ...
-- returns all received vararg parameters
return x,y,f()
-- returns x, y, and all results from f()
-- creates a list with all results from f()
-- creates a list with all vararg parameters
{f(), nil}
-- f() is adjusted to 1 result
Any expression enclosed in parentheses always results in only one value.
(f(x,y,z)) is always a single value,
even if f returns several values.
(The value of (f(x,y,z)) is the first value returned by f
or nil if f does not return any values.)
Lua supports the following arithmetic operators:
+: addition
-: subtraction
*: multiplication
/: float division
//: floor division
^: exponentiation
-: unary minus
With the exception of exponentiation and float division,
the arithmetic operators work as follows:
If both operands are integers,
the operation is performed over integers and the result is an integer.
Otherwise, if both operands are numbers
or strings that can be converted to
numbers (see ),
then they are converted to floats,
the operation is performed following the usual rules
for floating-point arithmetic
(usually the IEEE 754 standard),
and the result is a float.
Exponentiation and float division (/)
always convert their operands to floats
and the result is always a float.
Exponentiation uses the ISO&C function pow,
so that it works for non-integer exponents too.
Floor division (//) is a division
that rounds the quotient towards minus infinity,
that is, the floor of the division of its operands.
Modulo is defined as the remainder of a division
that rounds the quotient towards minus infinity (floor division).
In case of overflows in integer arithmetic,
all operations wrap around,
according to the usual rules of two-complement arithmetic.
(In other words,
they return the unique representable integer
that is equal modulo 264 to the mathematical result.)
Lua supports the following bitwise operators:
&: bitwise AND
|: bitwise OR
~: bitwise exclusive OR
&&: right shift
&&: left shift
~: unary bitwise NOT
All bitwise operations convert its operands to integers
operate on all bits of those integers,
and result in an integer.
Both right and left shifts fill the vacant bits with zeros.
Negative displacements shift to
displacements with absolute values equal to or higher than
the number of bits in an integer
result in zero (as all bits are shifted out).
Lua provides some automatic conversions between some
types and representations at run time.
Bitwise operators always convert float operands to integers.
Exponentiation and float division
always convert integer operands to floats.
All other arithmetic operations applied to mixed numbers
(integers and floats) convert the intege
this is called the usual rule.
The C API also converts both integers to floats and
floats to integers, as needed.
Moreover, string concatenation accepts numbers as arguments,
besides strings.
Lua also converts strings to numbers,
whenever a number is expected.
In a conversion from integer to float,
if the integer value has an exact representation as a float,
that is the result.
Otherwise,
the conversion gets the nearest higher or
the nearest lower representable value.
This kind of conversion never fails.
The conversion from float to integer
checks whether the float has an exact representation as an integer
(that is, the float has an integral value and
it is in the range of integer representation).
If it does, that representation is the result.
Otherwise, the conversion fails.
The conversion from strings to numbers goes as follows:
First, the string is converted to an integer or a float,
following its syntax and the rules of the Lua lexer.
(The string may have also leading and trailing spaces and a sign.)
Then, the resulting number (float or integer)
is converted to the type (float or integer) required by the context
(e.g., the operation that forced the conversion).
All conversions from strings to numbers
accept both a dot and the current locale mark
as the radix character.
(The Lua lexer, however, accepts only a dot.)
The conversion from numbers to strings uses a
non-specified human-readable format.
For complete control over how numbers are converted to strings,
use the format function from the string library
Lua supports the following relational operators:
==: equality
~=: inequality
&: less than
&: greater than
&=: less or equal
&=: greater or equal
These operators always result in false or true.
Equality (==) first compares the type of its operands.
If the types are different, then the result is false.
Otherwise, the values of the operands are compared.
Strings are compared in the obvious way.
Numbers are equal if they denote the same mathematical value.
Tables, userdata, and threads
are compared by reference:
two objects are considered equal only if they are the same object.
Every time you create a new object
(a table, userdata, or thread),
this new object is different from any previously existing object.
Closures with the same reference are always equal.
Closures with any detectable difference
(different behavior, different definition) are always different.
You can change the way that Lua compares tables and userdata
by using the "eq" metamethod (see ).
Equality comparisons do not convert strings to numbers
or vice versa.
Thus, "0"==0 evaluates to false,
and t[0] and t["0"] denote different
entries in a table.
The operator ~= is exactly the negation of equality (==).
The order operators work as follows.
If both arguments are numbers,
then they are compared according to their mathematical values
(regardless of their subtypes).
Otherwise, if both arguments are strings,
then their values are compared according to the current locale.
Otherwise, Lua tries to call the "lt" or the "le"
metamethod (see ).
A comparison a & b is translated to b & a
and a &= b is translated to b &= a.
Following the IEEE 754 standard,
NaN is considered neither smaller than,
nor equal to, nor greater than any value (including itself).
The logical operators in Lua are
and, or, and not.
Like the control structures (see ),
all logical operators consider both false and nil as false
and anything else as true.
The negation operator not always returns false or true.
The conjunction operator and returns its first argument
if this value is false or nil;
otherwise, and returns its second argument.
The disjunction operator or returns its first argument
if this value is different from nil and false;
otherwise, or returns its second argument.
Both and and or use short-
the second operand is evaluated only if necessary.
Here are some examples:
10 or error()
nil or "a"
nil and 10
false and error()
false and nil
false or nil
(In this manual,
--& indicates the result of the preceding expression.)
The 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 described in .
Otherwise, the __concat metamethod is called (see ).
The length operator is denoted by the unary prefix operator #.
The length of a string is its number of bytes
(that is, the usual meaning of string length when each
character is one byte).
The length operator applied on a table
returns a border in that table.
A border in a table t is any natural number
that satisfies the following condition:
(border == 0 or t[border] ~= nil) and t[border + 1] == nil
a border is any (natural) index in a table
where a non-nil value is followed by a nil value
(or zero, when index 1 is nil).
A table with exactly one border is called a sequence.
For instance, the table {10, 20, 30, 40, 50} is a sequence,
as it has only one border (5).
The table {10, 20, 30, nil, 50} has two borders (3 and 5),
and therefore it is not a sequence.
The table {nil, 20, 30, nil, nil, 60, nil}
has three borders (0, 3, and 6),
so it is not a sequence, too.
The table {} is a sequence with border 0.
Note that non-natural keys do not interfere
with whether a table is a sequence.
When t is a sequence,
#t returns its only border,
which corresponds to the intuitive notion of the length of the sequence.
When t is not a sequence,
#t can return any of its borders.
(The exact one depends on details of
the internal representation of the table,
which in turn can depend on how the table was populated and
the memory addresses of its non-numeric keys.)
The computation of the length of a table
has a guaranteed worst time of O(log n),
where n is the largest natural key in the table.
A program can modify the behavior of the length operator for
any value but strings through the __len metamethod (see ).
Operator precedence in Lua follows the table below,
from lower to higher priority:
unary operators (not
you can use parentheses to change the precedences of an expression.
The concatenation ('..') and exponentiation ('^')
operators are right associative.
All other binary operators are left associative.
Table constructors are expressions that create tables.
Every time a constructor is evaluated, a new table is created.
A constructor can be used to create an empty table
or to create a table and initialize some of its fields.
The general syntax for constructors is
tableconstructor ::= &{& [fieldlist] &}&
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= &[& exp &]& &=& exp | Name &=& exp | exp
fieldsep ::= &,& | &;&
Each field of the form [exp1] = exp2 adds to the new table an entry
with key exp1 and value exp2.
A field of the form name = exp is equivalent to
["name"] = exp.
Finally, fields of the form exp are equivalent to
[i] = exp, where i are consecutive integers
starting with 1.
Fields in the other formats do not affect this counting.
For example,
a = { [f(1)] = "x", "y"; x = 1, f(x), [30] = 23; 45 }
is equivalent to
local t = {}
t[f(1)] = g
t[1] = "x"
-- 1st exp
t[2] = "y"
-- 2nd exp
-- t["x"] = 1
t[3] = f(x)
-- 3rd exp
t[30] = 23
-- 4th exp
The order of the assignments in a constructor is undefined.
(This order would be relevant only when there are repeated keys.)
If the last field in the list has the form exp
and the expression is a function call or a vararg expression,
then all values returned by this expression enter the list consecutively
The field list can have an optional trailing separator,
as a convenience for machine-generated code.
A function call in Lua has the following syntax:
functioncall ::= prefixexp args
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.
Otherwise, the prefixexp "call" metamethod is called,
having as first parameter the value of prefixexp,
followed by the original call arguments
functioncall ::= prefixexp &:& Name args
can be used to call "methods".
A call v:name(args)
is syntactic sugar for v.name(v,args),
except that v is evaluated only once.
Arguments have the following syntax:
args ::= &(& [explist] &)&
args ::= tableconstructor
args ::= LiteralString
All argument expressions are evaluated before the call.
A call of the form f{fields} is
syntactic sugar for f({fields});
that is, the argument list is a single new table.
A 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.
A call of the form return functioncall is called
a tail call.
Lua implements proper tail calls
(or proper tail recursion):
in a tail call,
the called function reuses the stack entry of the calling function.
Therefore, there is no limit on the number of nested tail calls that
a program can execute.
However, a tail call erases any debug information about the
calling function.
Note that a tail call only happens with a particular syntax,
where the return has one single funct
this syntax makes the calling function return exactly
the returns of the called function.
So, none of the following examples are tail calls:
return (f(x))
-- results adjusted to 1
return 2 * f(x)
return x, f(x)
-- additional results
f(x); return
-- results discarded
return x or f(x)
-- results adjusted to 1
The syntax for function definition is
functiondef ::= function funcbody
funcbody ::= &(& [parlist] &)& block end
The following syntactic sugar simplifies function definitions:
stat ::= function funcname funcbody
stat ::= local function Name funcbody
funcname ::= Name {&.& Name} [&:& Name]
The statement
function f () body end
translates to
f = function () body end
The statement
function t.a.b.c.f () body end
translates to
t.a.b.c.f = function () body end
The statement
local function f () body end
translates to
f = function () body end
local f = function () body end
(This only makes a difference when the body of the function
contains references to f.)
A function definition is an executable expression,
whose value has type function.
When Lua precompiles a chunk,
all its function bodies are precompiled too.
Then, whenever Lua executes the function definition,
the function is instantiated (or closed).
This function instance (or closure)
is the final value of the expression.
Parameters act as local variables that are
initialized with the argument values:
parlist ::= namelist [&,& &...&] | &...&
When a function is called,
the list of arguments is adjusted to
the length of the list of parameters,
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 adju
instead, it collects all extra arguments and supplies them
to the function through a vararg expression,
which is also written as three dots.
The value of this expression is a list of all actual extra arguments,
similar to a function with multiple results.
If a vararg expression is used inside another expression
or in the middle of a list of expressions,
then its return list is adjusted to one element.
If the expression is used as the last element of a list of expressions,
then no adjustment is made
(unless that last expression is enclosed in parentheses).
As an example, consider the following definitions:
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
Then, we have the following mapping from arguments to parameters and
to the vararg expression:
PARAMETERS
a=3, b=nil
f(3, 4, 5)
f(r(), 10)
a=3, b=nil, ... --&
g(3, 4, 5, 8)
Results are returned using the return statement (see ).
If control reaches the end of a function
without encountering a return statement,
then the function returns with no results.
There is a system-dependent limit on the number of values
that a function may return.
This limit is guaranteed to be larger than 1000.
The colon syntax
is used for defining methods,
that is, functions that have an implicit extra parameter self.
Thus, the statement
function t.a.b.c:f (params) body end
is syntactic sugar for
t.a.b.c.f = function (self, params) body end
Lua is a lexically scoped language.
The scope of a local variable begins at the first statement after
its declaration and lasts until the last non-void statement
of the innermost block that includes the declaration.
Consider the following example:
-- global variable
-- new block
local x = x
-- new 'x', with value 10
-- another block
local x = x+1
-- another 'x'
(the global one)
Notice that, in a declaration like local x = x,
the new x being declared is not in scope yet,
and so the second x refers to the outside variable.
Because of the lexical scoping rules,
local variables can be freely accessed by functions
defined inside their scope.
A local variable used by an inner function is called
an upvalue, or external local variable,
inside the inner function.
Notice that each execution of a local statement
defines new local variables.
Consider the following example:
local x = 20
for i=1,10 do
local y = 0
a[i] = function () y=y+1; return x+y end
The loop creates ten closures
(that is, ten instances of the anonymous function).
Each of these closures uses a different y variable,
while all of them share the same x.
This section describes the C&API for Lua, that is,
the set of C&functions available to the host program to communicate
All API functions and related types and constants
are declared in the header file .
Even when we use the term "function",
any facility in the API may be provided as a macro instead.
Except where stated otherwise,
all such macros use each of their arguments exactly once
(except for the first argument, which is always a Lua state),
and so do not generate any hidden side-effects.
As in most C&libraries,
the Lua API functions do not check their arguments for validity or consistency.
However, you can change this behavior by compiling Lua
with the macro
The Lua library is fully reentrant:
it has no global variables.
It keeps all information it needs in a dynamic structure,
called the Lua state.
Each Lua state has one or more threads,
which correspond to independent, cooperative lines of execution.
(despite its name) refers to a thread.
(Indirectly, through the thread, it also refers to the
Lua state associated to the thread.)
A pointer to a thread must be passed as the first argument to
every function in the library, except to ,
which creates a Lua state from scratch and returns a pointer
to the main thread in the new state.
Lua uses a virtual stack to pass values to and from C.
Each element in this stack represents a Lua value
(nil, number, string, etc.).
Functions in the API can access this stack through the
Lua state parameter that they receive.
Whenever Lua calls C, the called function gets a new stack,
which is independent of previous stacks and of stacks of
C&functions that are still active.
This stack initially contains any arguments to the C&function
and it is where the C&function can store temporary
Lua values and must push its results
to be returned to the caller (see ).
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);
a negative index represents an offset relative to the top of the stack.
More specifically, if the stack has n elements,
then index&1 represents the first element
(that is, the element that was pushed onto the stack first)
index&n represe
index&-1 also represents the last element
(that is, the element at the&top)
and index -n represents the first element.
When you interact with the Lua API,
you are responsible for ensuring consistency.
In particular,
you are responsible for controlling stack overflow.
You can use the function
to ensure that the stack has enough space for pushing new elements.
Whenever Lua calls C,
it ensures that the stack has space for
extra slots.
LUA_MINSTACK is defined as 20,
so that usually you do not have to worry about stack space
unless your code has loops pushing elements onto the stack.
When you call a Lua function
without a fixed number of results (see ),
Lua ensures that the stack has enough space for all results,
but it does not ensure any extra space.
So, before pushing anything in the stack after such a call
you should use .
Any function in the API that receives stack indices
works only with valid indices or acceptable indices.
A valid index is an index that refers to a
position that stores a modifiable Lua value.
It comprises stack indices between&1 and the stack top
(1 & abs(index) & top)
plus pseudo-indices,
which represent some positions that are accessible to C&code
but that are not in the stack.
Pseudo-indices are used to access the registry (see )
and the upvalues of a C&function (see ).
Functions that do not need a specific mutable position,
but only a value (e.g., query functions),
can be called with acceptable indices.
An acceptable index can be any valid index,
but it also can be any positive index after the stack top
within the space allocated for the stack,
that is, indices up to the stack size.
(Note that 0 is never an acceptable index.)
Except when noted otherwise,
functions in the API work with acceptable indices.
Acceptable indices serve to avoid extra tests
against the stack top when querying the stack.
For instance, a C&function can query its third argument
without the need to first check whether there is a third argument,
that is, without the need to check whether 3 is a valid index.
For functions that can be called with acceptable indices,
any non-valid index is treated as if it
contains a value of a virtual type ,
which behaves like a nil value.
When a C&function is created,
it is possible to associate some values with it,
thus creating a C&closure
these values are called upvalues and are
accessible to the function whenever it is called.
Whenever a C&function is called,
its upvalues are located at specific pseudo-indices.
These pseudo-indices are produced by the macro
The first upvalue associated with a function is at index
lua_upvalueindex(1), and so on.
Any access to lua_upvalueindex(n),
where n is greater than the number of upvalues of the
current function
(but not greater than 256,
which is one plus the maximum number of upvalues in a closure),
produces an acceptable but invalid index.
Lua provides a registry,
a predefined table that can be used by any C&code to
store whatever Lua values it needs to store.
The registry table is always located at pseudo-index
Any C&library can store data into this table,
but it must take care to choose keys
that are different from those used
by other libraries, to avoid collisions.
Typically, you should use as key a string containing your library name,
or a light userdata with the address of a C&object in your code,
or any Lua object created by your code.
As with variable names,
string keys starting with an underscore followed by
uppercase letters are reserved for Lua.
The integer keys in the registry are used
by the reference mechanism (see )
and by some predefined values.
Therefore, integer keys must not be used for other purposes.
When you create a new Lua state,
its registry comes with some predefined values.
These predefined values are indexed with integer keys
defined as constants in lua.h.
The following constants are defined:
At this index the registry has
the main thread of the state.
(The mai}

我要回帖

更多关于 useasyncsend 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信