l hook: is called when the interpreter calls a function. The hook is called just after Lua enters the new function, before the function gets its arguments.
count
instructions.
(This event only happens while Lua is executing a Lua function.)
A hook is disabled by setting mask
to zero.
lua_setlocal
[-(0|1), +0, -]
const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);
Sets the value of a local variable of a given activation record.
Parameters ar
and n
are as in lua_getlocal
(see lua_getlocal
).
lua_setlocal
assigns the value at the top of the stack
to the variable and returns its name.
It also pops the value from the stack.
Returns NULL
(and pops nothing)
when the index is greater than
the number of active local variables.
lua_setupvalue
[-(0|1), +0, -]
const char *lua_setupvalue (lua_State *L, int funcindex, int n);
Sets the value of a closure's upvalue.
It assigns the value at the top of the stack
to the upvalue and returns its name.
It also pops the value from the stack.
Parameters funcindex
and n
are as in the lua_getupvalue
(see lua_getupvalue
).
Returns NULL
(and pops nothing)
when the index is greater than the number of upvalues.
The auxiliary library provides several convenient functions to interface C with Lua. While the basic API provides the primitive functions for all interactions between C and Lua, the auxiliary library provides higher-level functions for some common tasks.
All functions from the auxiliary library
are defined in header file lauxlib.h
and
have a prefix luaL_
.
All functions in the auxiliary library are built on top of the basic API, and so they provide nothing that cannot be done with this API.
Several functions in the auxiliary library are used to
check C function arguments.
Their names are always luaL_check*
or luaL_opt*
.
All of these functions throw an error if the check is not satisfied.
Because the error message is formatted for arguments
(e.g., "bad argument #1
"),
you should not use these functions for other stack values.
Here we list all functions and types from the auxiliary library in alphabetical order.
luaL_addchar
[-0, +0, m]
void luaL_addchar (luaL_Buffer *B, char c);
Adds the character c
to the buffer B
(see luaL_Buffer
).
luaL_addlstring
[-0, +0, m]
void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
Adds the string pointed to by s
with length l
to
the buffer B
(see luaL_Buffer
).
The string may contain embedded zeros.
luaL_addsize
[-0, +0, m]
void luaL_addsize (luaL_Buffer *B, size_t n);
Adds to the buffer B
(see luaL_Buffer
)
a string of length n
previously copied to the
buffer area (see luaL_prepbuffer
).
luaL_addstring
[-0, +0, m]
void luaL_addstring (luaL_Buffer *B, const char *s);
Adds the zero-terminated string pointed to by s
to the buffer B
(see luaL_Buffer
).
The string may not contain embedded zeros.
luaL_addvalue
[-1, +0, m]
void luaL_addvalue (luaL_Buffer *B);
Adds the value at the top of the stack
to the buffer B
(see luaL_Buffer
).
Pops the value.
This is the only function on string buffers that can (and must) be called with an extra element on the stack, which is the value to be added to the buffer.
luaL_argcheck
[-0, +0, v]
void luaL_argcheck (lua_State *L, int cond, int narg, const char *extramsg);
Checks whether cond
is true.
If not, raises an error with the following message,
where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
luaL_argerror
[-0, +0, v]
int luaL_argerror (lua_State *L, int narg, const char *extramsg);
Raises an error with the following message,
where func
is retrieved from the call stack:
bad argument #<narg> to <func> (<extramsg>)
This function never returns,
but it is an idiom to use it in C functions
as return luaL_argerror(args)
.
luaL_Buffer
typedef struct luaL_Buffer luaL_Buffer;
Type for a string buffer.
A string buffer allows C code to build Lua strings piecemeal. Its pattern of use is as follows:
b
of type luaL_Buffer
.luaL_buffinit(L, &b)
.luaL_add*
functions.
luaL_pushresult(&b)
.
This call leaves the final string on the top of the stack.
During its normal operation,
a string buffer uses a variable number of stack slots.
So, while using a buffer, you cannot assume that you know where
the top of the stack is.
You can use the stack between successive calls to buffer operations
as long as that use is balanced;
that is,
when you call a buffer operation,
the stack is at the same level
it was immediately after the previous buffer operation.
(The only exception to this rule is luaL_addvalue
.)
After calling luaL_pushresult
the stack is back to its
level when the buffer was initialized,
plus the final string on its top.
luaL_buffinit
[-0, +0, -]
void luaL_buffinit (lua_State *L, luaL_Buffer *B);
Initializes a buffer B
.
This function does not allocate any space;
the buffer must be declared as a variable
(see luaL_Buffer
).
luaL_callmeta
[-0, +(0|1), e]
int luaL_callmeta (lua_State *L, int obj, const char *e);
Calls a metamethod.
If the object at index obj
has a metatable and this
metatable has a field e
,
this function calls this field and passes the object as its only argument.
In this case this function returns 1 and pushes onto the
stack the value returned by the call.
If there is no metatable or no metamethod,
this function returns 0 (without pushing any value on the stack).
luaL_checkany
[-0, +0, v]
void luaL_checkany (lua_State *L, int narg);
Checks whether the function has an argument
of any type (including nil) at position narg
.
luaL_checkint
[-0, +0, v]
int luaL_checkint (lua_State *L, int narg);
Checks whether the function argument narg
is a number
and returns this number cast to an int
.
luaL_checkinteger
[-0, +0, v]
lua_Integer luaL_checkinteger (lua_State *L, int narg);
Checks whether the function argument narg
is a number
and returns this number cast to a lua_Integer
.
luaL_checklong
[-0, +0, v]
long luaL_checklong (lua_State *L, int narg);
Checks whether the function argument narg
is a number
and returns this number cast to a long
.
luaL_checklstring
[-0, +0, v]
const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
Checks whether the function argument narg
is a string
and returns this string;
if l
is not NULL
fills *l
with the string's length.
This function uses lua_tolstring
to get its result,
so all conversions and caveats of that function apply here.
luaL_checknumber
[-0, +0, v]
lua_Number luaL_checknumber (lua_State *L, int narg);
Checks whether the function argument narg
is a number
and returns this number.
luaL_checkoption
[-0, +0, v]
int luaL_checkoption (lua_State *L, int narg, const char *def, const char *const lst[]);
Checks whether the function argument narg
is a string and
searches for this string in the array lst
(which must be NULL-terminated).
Returns the index in the array where the string was found.
Raises an error if the argument is not a string or
if the string cannot be found.
If def
is not NULL
,
the function uses def
as a default value when
there is no argument narg
or if this argument is nil.
This is a useful function for mapping strings to C enums. (The usual convention in Lua libraries is to use strings instead of numbers to select options.)
luaL_checkstack
[-0, +0, v]
void luaL_checkstack (lua_State *L, int sz, const char *msg);
Grows the stack size to top + sz
elements,
raising an error if the stack cannot grow to that size.
msg
is an additional text to go into the error message.
luaL_checkstring
[-0, +0, v]
const char *luaL_checkstring (lua_State *L, int narg);
Checks whether the function argument narg
is a string
and returns this string.
This function uses lua_tolstring
to get its result,
so all conversions and caveats of that function apply here.
luaL_checktype
[-0, +0, v]
void luaL_checktype (lua_State *L, int narg, int t);
Checks whether the function argument narg
has type t
.
See lua_type
for the encoding of types for t
.
luaL_checkudata
[-0, +0, v]
void *luaL_checkudata (lua_State *L, int narg, const char *tname);
Checks whether the function argument narg
is a userdata
of the type tname
(see luaL_newmetatable
).
luaL_dofile
[-0, +?, m]
int luaL_dofile (lua_State *L, const char *filename);
Loads and runs the given file. It is defined as the following macro:
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_dostring
[-0, +?, m]
int luaL_dostring (lua_State *L, const char *str);
Loads and runs the given string. It is defined as the following macro:
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
It returns 0 if there are no errors or 1 in case of errors.
luaL_error
[-0, +0, v]
int luaL_error (lua_State *L, const char *fmt, ...);
Raises an error.
The error message format is given by fmt
plus any extra arguments,
following the same rules of lua_pushfstring
.
It also adds at the beginning of the message the file name and
the line number where the error occurred,
if this information is available.
This function never returns,
but it is an idiom to use it in C functions
as return luaL_error(args)
.
luaL_getmetafield
[-0, +(0|1), m]
int luaL_getmetafield (lua_State *L, int obj, const char *e);
Pushes onto the stack the field e
from the metatable
of the object at index obj
.
If the object does not have a metatable,
or if the metatable does not have this field,
returns 0 and pushes nothing.
luaL_getmetatable
[-0, +1, -]
void luaL_getmetatable (lua_State *L, const char *tname);
Pushes onto the stack the metatable associated with name tname
in the registry (see luaL_newmetatable
).
luaL_gsub
[-0, +1, m]
const char *luaL_gsub (lua_State *L, const char *s, const char *p, const char *r);
Creates a copy of string s
by replacing
any occurrence of the string p
with the string r
.
Pushes the resulting string on the stack and returns it.
luaL_loadbuffer
[-0, +1, m]
int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz, const char *name);
Loads a buffer as a Lua chunk.
This function uses lua_load
to load the chunk in the
buffer pointed to by buff
with size sz
.
This function returns the same results as lua_load
.
name
is the chunk name,
used for debug information and error messages.
luaL_loadfile
[-0, +1, m]
int luaL_loadfile (lua_State *L, const char *filename);
Loads a file as a Lua chunk.
This function uses lua_load
to load the chunk in the file
named filename
.
If filename
is NULL
,
then it loads from the standard input.
The first line in the file is ignored if it starts with a #
.
This function returns the same results as lua_load
,
but it has an extra error code LUA_ERRFILE
if it cannot open/read the file.
As lua_load
, this function only loads the chunk;
it does not run it.
luaL_loadstring
[-0, +1, m]
int luaL_loadstring (lua_State *L, const char *s);
Loads a string as a Lua chunk.
This function uses lua_load
to load the chunk in
the zero-terminated string s
.
This function returns the same results as lua_load
.
Also as lua_load
, this function only loads the chunk;
it does not run it.
luaL_newmetatable
[-0, +1, m]
int luaL_newmetatable (lua_State *L, const char *tname);
If the registry already has the key tname
,
returns 0.
Otherwise,
creates a new table to be used as a metatable for userdata,
adds it to the registry with key tname
,
and returns 1.
In both cases pushes onto the stack the final value associated
with tname
in the registry.
luaL_newstate
[-0, +0, -]
lua_State *luaL_newstate (void);
Creates a new Lua state.
It calls lua_newstate
with an
allocator based on the standard C realloc
function
and then sets a panic function (see lua_atpanic
) that prints
an error message to the standard error output in case of fatal
errors.
Returns the new state,
or NULL
if there is a memory allocation error.
luaL_openlibs
[-0, +0, m]
void luaL_openlibs (lua_State *L);
Opens all standard Lua libraries into the given state.
luaL_optint
[-0, +0, v]
int luaL_optint (lua_State *L, int narg, int d);
If the function argument narg
is a number,
returns this number cast to an int
.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
luaL_optinteger
[-0, +0, v]
lua_Integer luaL_optinteger (lua_State *L, int narg, lua_Integer d);
If the function argument narg
is a number,
returns this number cast to a lua_Integer
.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
luaL_optlong
[-0, +0, v]
long luaL_optlong (lua_State *L, int narg, long d);
If the function argument narg
is a number,
returns this number cast to a long
.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
luaL_optlstring
[-0, +0, v]
const char *luaL_optlstring (lua_State *L, int narg, const char *d, size_t *l);
If the function argument narg
is a string,
returns this string.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
If l
is not NULL
,
fills the position *l
with the results's length.
luaL_optnumber
[-0, +0, v]
lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number d);
If the function argument narg
is a number,
returns this number.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
luaL_optstring
[-0, +0, v]
const char *luaL_optstring (lua_State *L, int narg, const char *d);
If the function argument narg
is a string,
returns this string.
If this argument is absent or is nil,
returns d
.
Otherwise, raises an error.
luaL_prepbuffer
[-0, +0, -]
char *luaL_prepbuffer (luaL_Buffer *B);
Returns an address to a space of size LUAL_BUFFERSIZE
where you can copy a string to be added to buffer B
(see luaL_Buffer
).
After copying the string into this space you must call
luaL_addsize
with the size of the string to actually add
it to the buffer.
luaL_pushresult
[-?, +1, m]
void luaL_pushresult (luaL_Buffer *B);
Finishes the use of buffer B
leaving the final string on
the top of the stack.
luaL_ref
[-1, +0, m]
int luaL_ref (lua_State *L, int t);
Creates and returns a reference,
in the table at index t
,
for the object at the top of the stack (and pops the object).
A reference is a unique integer key.
As long as you do not manually add integer keys into table t
,
luaL_ref
ensures the uniqueness of the key it returns.
You can retrieve an object referred by reference r
by calling lua_rawgeti(L, t, r)
.
Function luaL_unref
frees a reference and its associated object.
If the object at the top of the stack is nil,
luaL_ref
returns the constant LUA_REFNIL
.
The constant LUA_NOREF
is guaranteed to be different
from any reference returned by luaL_ref
.
luaL_Reg
typedef struct luaL_Reg { const char *name; lua_CFunction func; } luaL_Reg;
Type for arrays of functions to be registered by
luaL_register
.
name
is the function name and func
is a pointer to
the function.
Any array of luaL_Reg
must end with an sentinel entry
in which both name
and func
are NULL
.
luaL_register
[-(0|1), +1, m]
void luaL_register (lua_State *L, const char *libname, const luaL_Reg *l);
Opens a library.
When called with libname
equal to NULL
,
it simply registers all functions in the list l
(see luaL_Reg
) into the table on the top of the stack.
When called with a non-null libname
,
luaL_register
creates a new table t
,
sets it as the value of the global variable libname
,
sets it as the value of package.loaded[libname]
,
and registers on it all functions in the list l
.
If there is a table in package.loaded[libname]
or in
variable libname
,
reuses this table instead of creating a new one.
In any case the function leaves the table on the top of the stack.
luaL_typename
[-0, +0, -]
const char *luaL_typename (lua_State *L, int index);
Returns the name of the type of the value at the given index.
luaL_typerror
[-0, +0, v]
int luaL_typerror (lua_State *L, int narg, const char *tname);
Generates an error with a message like the following:
location: bad argument narg to 'func' (tname expected, got rt)
where location
is produced by luaL_where
,
func
is the name of the current function,
and rt
is the type name of the actual argument.
luaL_unref
[-0, +0, -]
void luaL_unref (lua_State *L, int t, int ref);
Releases reference ref
from the table at index t
(see luaL_ref
).
The entry is removed from the table,
so that the referred object can be collected.
The reference ref
is also freed to be used again.
If ref
is LUA_NOREF
or LUA_REFNIL
,
luaL_unref
does nothing.
luaL_where
[-0, +1, m]
void luaL_where (lua_State *L, int lvl);
Pushes onto the stack a string identifying the current position
of the control at level lvl
in the call stack.
Typically this string has the following format:
chunkname:currentline:
Level 0 is the running function, level 1 is the function that called the running function, etc.
This function is used to build a prefix for error messages.
The standard Lua libraries provide useful functions
that are implemented directly through the C API.
Some of these functions provide essential services to the language
(e.g., type
and getmetatable
);
others provide access to "outside" services (e.g., I/O);
and others could be implemented in Lua itself,
but are quite useful or have critical performance requirements that
deserve an implementation in C (e.g., table.sort
).
All libraries are implemented through the official C API and are provided as separate C modules. Currently, Lua has the following standard libraries:
Except for the basic and package libraries, each library provides all its functions as fields of a global table or as methods of its objects.
To have access to these libraries,
the C host program should call the luaL_openlibs
function,
which opens all standard libraries.
Alternatively,
it can open them individually by calling
luaopen_base
(for the basic library),
luaopen_package
(for the package library),
luaopen_string
(for the string library),
luaopen_table
(for the table library),
luaopen_math
(for the mathematical library),
luaopen_io
(for the I/O library),
luaopen_os
(for the Operating System library),
and luaopen_debug
(for the debug library).
These functions are declared in lualib.h
and should not be called directly:
you must call them like any other Lua C function,
e.g., by using lua_call
.
The basic library provides some core functions to Lua. If you do not include this library in your application, you should check carefully whether you need to provide implementations for some of its facilities.
assert (v [, message])
v
is false (i.e., nil or false);
otherwise, returns all its arguments.
message
is an error message;
when absent, it defaults to "assertion failed!"
collectgarbage (opt [, arg])
This function is a generic interface to the garbage collector.
It performs different functions according to its first argument, opt
:
arg
(larger values mean more steps) in a non-specified way.
If you want to control the step size
you must experimentally tune the value of arg
.
Returns true if the step finished a collection cycle.
arg
as the new value for the pause of
the collector (see §2.10).
Returns the previous value for pause.
arg
as the new value for the step multiplier of
the collector (see §2.10).
Returns the previous value for step.
dofile (filename)
dofile
executes the contents of the standard input (stdin
).
Returns all values returned by the chunk.
In case of errors, dofile
propagates the error
to its caller (that is, dofile
does not run in protected mode).
error (message [, level])
message
as the error message.
Function error
never returns.
Usually, error
adds some information about the error position
at the beginning of the message.
The level
argument specifies how to get the error position.
With level 1 (the default), the error position is where the
error
function was called.
Level 2 points the error to where the function
that called error
was called; and so on.
Passing a level 0 avoids the addition of error position information
to the message.
_G
_G._G = _G
).
Lua itself does not use this variable;
changing its value does not affect any environment,
nor vice-versa.
(Use setfenv
to change environments.)
getfenv ([f])
f
can be a Lua function or a number
that specifies the function at that stack level:
Level 1 is the function calling getfenv
.
If the given function is not a Lua function,
or if f
is 0,
getfenv
returns the global environment.
The default for f
is 1.
getmetatable (object)
If object
does not have a metatable, returns nil.
Otherwise,
if the object's metatable has a "__metatable"
field,
returns the associated value.
Otherwise, returns the metatable of the given object.
ipairs (t)
Returns three values: an iterator function, the table t
, and 0,
so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]
), (2,t[2]
), ···,
up to the first integer key absent from the table.
load (func [, chunkname])
Loads a chunk using function func
to get its pieces.
Each call to func
must return a string that concatenates
with previous results.
A return of an empty string, nil, or no value signals the end of the chunk.
If there are no errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message. The environment of the returned function is the global environment.
chunkname
is used as the chunk name for error messages
and debug information.
When absent,
it defaults to "=(load)
".
loadfile ([filename])
Similar to load
,
but gets the chunk from file filename
or from the standard input,
if no file name is given.
loadstring (string [, chunkname])
Similar to load
,
but gets the chunk from the given string.
To load and run a given string, use the idiom
assert(loadstring(s))()
When absent,
chunkname
defaults to the given string.
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 its associated value.
When called with nil as its second argument,
next
returns an initial index
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.
In particular,
you can use next(t)
to check whether a table is empty.
The order in which the indices are enumerated is not specified,
even for numeric indices.
(To traverse a table in numeric order,
use a numerical for or the ipairs
function.)
The behavior of next
is undefined if,
during the traversal,
you assign any value to a non-existent field in the table.
You may however modify existing fields.
In particular, you may clear existing fields.
pairs (t)
Returns three values: the next
function, the table t
, and nil,
so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t
.
See function next
for the caveats of modifying
the table during its traversal.
pcall (f, arg1, ···)
Calls function f
with
the given arguments in protected mode.
This means that any error inside f
is not propagated;
instead, pcall
catches the error
and returns a status code.
Its first result is the status code (a boolean),
which is true if the call succeeds without errors.
In such case, pcall
also returns all results from the call,
after this first result.
In case of any error, pcall
returns false plus the error message.
print (···)
stdout
,
using the tostring
function to convert them to strings.
print
is not intended for formatted output,
but only as a quick way to show a value,
typically for debugging.
For formatted output, use string.format
.
rawequal (v1, v2)
v1
is equal to v2
,
without invoking any metamethod.
Returns a boolean.
rawget (table, index)
table[index]
,
without invoking any metamethod.
table
must be a table;
index
may be any value.
rawset (table, index, value)
table[index]
to value
,
without invoking any metamethod.
table
must be a table,
index
any value different from nil,
and value
any Lua value.
This function returns table
.
select (index, ···)
If index
is a number,
returns all arguments after argument number index
.
Otherwise, index
must be the string "#"
,
and select
returns the total number of extra arguments it received.
setfenv (f, table)
Sets the environment to be used by the given function.
f
can be a Lua function or a number
that specifies the function at that stack level:
Level 1 is the function calling setfenv
.
setfenv
returns the given function.
As a special case, when f
is 0 setfenv
changes
the environment of the running thread.
In this case, setfenv
returns no values.
setmetatable (table, metatable)
Sets the metatable for the given table.
(You cannot change the metatable of other types from Lua, only from C.)
If metatable
is nil,
removes the metatable of the given table.
If the original metatable has a "__metatable"
field,
raises an error.
This function returns table
.
tonumber (e [, base])
tonumber
returns this 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
' (in either upper or lower case)
represents 10, 'B
' represents 11, and so forth,
with 'Z
' representing 35.
In base 10 (the default), the number can have a decimal part,
as well as an optional exponent part (see §2.1).
In other bases, only unsigned integers are accepted.
tostring (e)
string.format
.
If the metatable of e
has a "__tostring"
field,
then tostring
calls the corresponding value
with e
as argument,
and uses the result of the call as its result.
type (v)
nil
" (a string, not the value nil),
"number
",
"string
",
"boolean
",
"table
",
"function
",
"thread
",
and "userdata
".
unpack (list [, i [, j]])
return list[i], list[i+1], ···, list[j]
except that the above code can be written only for a fixed number
of elements.
By default, i
is 1 and j
is the length of the list,
as defined by the length operator (see §2.5.5).
_VERSION
Lua 5.1
".
xpcall (f, err)
This function is similar to pcall
,
except that you can set a new error handler.
xpcall
calls function f
in protected mode,
using err
as the error handler.
Any error inside f
is not propagated;
instead, xpcall
catches the error,
calls the err
function with the original error object,
and returns a status code.
Its first result is the status code (a boolean),
which is true if the call succeeds without errors.
In this case, xpcall
also returns all results from the call,
after this first result.
In case of any error,
xpcall
returns false plus the result from err
.
The operations related to coroutines comprise a sub-library of
the basic library and come inside the table coroutine
.
See §2.11 for a general description of coroutines.
coroutine.create (f)
Creates a new coroutine, with body f
.
f
must be a Lua function.
Returns this new coroutine,
an object with type "thread"
.
coroutine.resume (co [, val1, ···])
Starts or continues the execution of coroutine co
.
The first time you resume a coroutine,
it starts running its body.
The values val1
, ··· are passed
as the arguments to the body function.
If the coroutine has yielded,
resume
restarts it;
the values val1
, ··· are passed
as the results from the yield.
If the coroutine runs without any errors,
resume
returns true plus any values passed to yield
(if the coroutine yields) or any values returned by the body function
(if the coroutine terminates).
If there is any error,
resume
returns false plus the error message.
coroutine.running ()
Returns the running coroutine, or nil when called by the main thread.
coroutine.status (co)
Returns the status of coroutine co
, as a string:
"running"
,
if the coroutine is running (that is, it called status
);
"suspended"
, if the coroutine is suspended in a call to yield
,
or if it has not started running yet;
"normal"
if the coroutine is active but not running
(that is, it has resumed another coroutine);
and "dead"
if the coroutine has finished its body function,
or if it has stopped with an error.
coroutine.wrap (f)
Creates a new coroutine, with body f
.
f
must be a Lua function.
Returns a function that resumes the coroutine each time it is called.
Any arguments passed to the function behave as the
extra arguments to resume
.
Returns the same values returned by resume
,
except the first boolean.
In case of error, propagates the error.
coroutine.yield (···)
Suspends the execution of the calling coroutine.
The coroutine cannot be running a C function,
a metamethod, or an iterator.
Any arguments to yield
are passed as extra results to resume
.
The package library provides basic
facilities for loading and building modules in Lua.
It exports two of its functions directly in the global environment:
require
and module
.
Everything else is exported in a table package
.
module (name [, ···])
Creates a module.
If there is a table in package.loaded[name]
,
this table is the module.
Otherwise, if there is a global table t
with the given name,
this table is the module.
Otherwise creates a new table t
and
sets it as the value of the global name
and
the value of package.loaded[name]
.
This function also initializes t._NAME
with the given name,
t._M
with the module (t
itself),
and t._PACKAGE
with the package name
(the full module name minus last component; see below).
Finally, module
sets t
as the new environment
of the current function and the new value of package.loaded[name]
,
so that require
returns t
.
If name
is a compound name
(that is, one with components separated by dots),
module
creates (or reuses, if they already exist)
tables for each component.
For instance, if name
is a.b.c
,
then module
stores the module table in field c
of
field b
of global a
.
This function can receive optional options after the module name, where each option is a function to be applied over the module.
require (modname)
Loads the given module.
The function starts by looking into the package.loaded
table
to determine whether modname
is already loaded.
If it is, then require
returns the value stored
at package.loaded[modname]
.
Otherwise, it tries to find a loader for the module.
To find a loader,
require
is guided by the package.loaders
array.
By changing this array,
we can change how require
looks for a module.
The following explanation is based on the default configuration
for package.loaders
.
First require
queries package.preload[modname]
.
If it has a value,
this value (which should be a function) is the loader.
Otherwise require
searches for a Lua loader using the
path stored in package.path
.
If that also fails, it searches for a C loader using the
path stored in package.cpath
.
If that also fails,
it tries an all-in-one loader (see package.loaders
).
Once a loader is found,
require
calls the loader with a single argument, modname
.
If the loader returns any value,
require
assigns the returned value to package.loaded[modname]
.
If the loader returns no value and
has not assigned any value to package.loaded[modname]
,
then require
assigns true to this entry.
In any case, require
returns the
final value of package.loaded[modname]
.
If there is any error loading or running the module,
or if it cannot find any loader for the module,
then require
signals an error.
package.cpath
The path used by require
to search for a C loader.
Lua initializes the C path package.cpath
in the same way
it initializes the Lua path package.path
,
using the environment variable LUA_CPATH
or a default path defined in luaconf.h
.
package.loaded
A table used by require
to control which
modules are already loaded.
When you require a module modname
and
package.loaded[modname]
is not false,
require
simply returns the value stored there.
package.loaders
A table used by require
to control how to load modules.
Each entry in this table is a searcher function.
When looking for a module,
require
calls each of these searchers in ascending order,
with the module name (the argument given to require
) as its
sole parameter.
The function can return another function (the module loader)
or a string explaining why it did not find that module
(or nil if it has nothing to say).
Lua initializes this table with four functions.
The first searcher simply looks for a loader in the
package.preload
table.
The second searcher looks for a loader as a Lua library,
using the path stored at package.path
.
A path is a sequence of templates separated by semicolons.
For each template,
the searcher will change each interrogation
mark in the template by filename
,
which is the module name with each dot replaced by a
"directory separator" (such as "/
" in Unix);
then it will try to open the resulting file name.
So, for instance, if the Lua path is the string
"./?.lua;./?.lc;/usr/local/?/init.lua"
the search for a Lua file for module foo
will try to open the files
./foo.lua
, ./foo.lc
, and
/usr/local/foo/init.lua
, in that order.
The third searcher looks for a loader as a C library,
using the path given by the variable package.cpath
.
For instance,
if the C path is the string
"./?.so;./?.dll;/usr/local/?/init.so"
the searcher for module foo
will try to open the files ./foo.so
, ./foo.dll
,
and /usr/local/foo/init.so
, in that order.
Once it finds a C library,
this searcher first uses a dynamic link facility to link the
application with the library.
Then it tries to find a C function inside the library to
be used as the loader.
The name of this C function is the string "luaopen_
"
concatenated with a copy of the module name where each dot
is replaced by an underscore.
Moreover, if the module name has a hyphen,
its prefix up to (and including) the first hyphen is removed.
For instance, if the module name is a.v1-b.c
,
the function name will be luaopen_b_c
.
The fourth searcher tries an all-in-one loader.
It searches the C path for a library for
the root name of the given module.
For instance, when requiring a.b.c
,
it will search for a C library for a
.
If found, it looks into it for an open function for
the submodule;
in our example, that would be luaopen_a_b_c
.
With this facility, a package can pack several C submodules
into one single library,
with each submodule keeping its original open function.
package.loadlib (libname, funcname)
Dynamically links the host program with the C library libname
.
Inside this library, looks for a function funcname
and returns this function as a C function.
(So, funcname
must follow the protocol (see lua_CFunction
)).
This is a low-level function.
It completely bypasses the package and module system.
Unlike require
,
it does not perform any path searching and
does not automatically adds extensions.
libname
must be the complete file name of the C library,
including if necessary a path and extension.
funcname
must be the exact name exported by the C library
(which may depend on the C compiler and linker used).
This function is not supported by ANSI C.
As such, it is only available on some platforms
(Windows, Linux, Mac OS X, Solaris, BSD,
plus other Unix systems that support the dlfcn
standard).
package.path
The path used by require
to search for a Lua loader.
At start-up, Lua initializes this variable with
the value of the environment variable LUA_PATH
or
with a default path defined in luaconf.h
,
if the environment variable is not defined.
Any ";;
" in the value of the environment variable
is replaced by the default path.
package.preload
A table to store loaders for specific modules
(see require
).
package.seeall (module)
Sets a metatable for module
with
its __index
field referring to the global environment,
so that this module inherits values
from the global environment.
To be used as an option to function module
.
This library provides generic functions for string manipulation, such as finding and extracting substrings, and pattern matching. When indexing a string in Lua, the first character is at position 1 (not at 0, as in C). Indices are allowed to be negative and are interpreted as indexing backwards, from the end of the string. Thus, the last character is at position -1, and so on.
The string library provides all its functions inside the table
string
.
It also sets a metatable for strings
where the __index
field points to the string
table.
Therefore, you can use the string functions in object-oriented style.
For instance, string.byte(s, i)
can be written as s:byte(i)
.
The string library assumes one-byte character encodings.
string.byte (s [, i [, j]])
s[i]
,
s[i+1]
, ···, s[j]
.
The default value for i
is 1;
the default value for j
is i
.
Note that numerical codes are not necessarily portable across platforms.
string.char (···)
Note that numerical codes are not necessarily portable across platforms.
string.dump (function)
Returns a string containing a binary representation of the given function,
so that a later loadstring
on this string returns
a copy of the function.
function
must be a Lua function without upvalues.
string.find (s, pattern [, init [, plain]])
pattern
in the string s
.
If it finds a match, then find
returns the indices of s
where this occurrence starts and ends;
otherwise, it returns nil.
A third, optional numerical argument init
specifies
where to start the search;
its default value is 1 and can be negative.
A value of true 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 as well.
If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.
string.format (formatstring, ···)
printf
family of
standard C functions.
The only differences are that the options/modifiers
*
, l
, L
, n
, p
,
and h
are not supported
and that 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, newlines, embedded zeros,
and backslashes in the string
are correctly escaped when written.
For instance, the call
string.format('%q', 'a string with "quotes" and \n new line')
will produce the string:
"a string with \"quotes\" and \ new line"
The options c
, d
, E
, e
, f
,
g
, G
, i
, o
, u
, X
, and x
all
expect a number as argument,
whereas q
and s
expect a string.
This function does not accept string values
containing embedded zeros,
except as arguments to the q
option.
string.gmatch (s, pattern)
pattern
over string s
.
If pattern
specifies no captures,
then the whole match is produced in each call.
As an example, the following loop
s = "hello world from Lua" for w in string.gmatch(s, "%a+") do print(w) end
will iterate over all the words from string s
,
printing one per line.
The next example collects all pairs key=value
from the
given string into a table:
t = {} s = "from=world, to=Lua" for k, v in string.gmatch(s, "(%w+)=(%w+)") do t[k] = v end
For this function, a '^
' at the start of a pattern does not
work as an anchor, as this would prevent the iteration.
string.gsub (s, pattern, repl [, n])
s
in which all (or the first n
, if given)
occurrences of the pattern
have been
replaced by a replacement string specified by repl
,
which can be a string, a table, or a function.
gsub
also returns, as its second value,
the total number of matches that occurred.
If repl
is a string, then its value is used for replacement.
The character %
works as an escape character:
any sequence in repl
of the form %n
,
with n between 1 and 9,
stands for the value of the n-th captured substring (see below).
The sequence %0
stands for the whole match.
The sequence %%
stands for a single %
.
If repl
is a table, then the table is queried for every match,
using the first capture as the key;
if the pattern specifies no captures,
then the whole match is used as the key.
If repl
is a function, then this function is called every time a
match occurs, with all captured substrings passed as arguments,
in order;
if the pattern specifies no captures,
then the whole match is passed as a sole argument.
If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).
Here are some examples:
x = string.gsub("hello world", "(%w+)", "%1 %1") --> x="hello hello world world" x = string.gsub("hello world", "%w+", "%0 %0", 1) --> x="hello hello world" x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1") --> x="world hello Lua from" x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv) --> x="home = /home/roberto, user = roberto" x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s) return loadstring(s)() end) --> x="4+5 = 9" local t = {name="lua", version="5.1"} x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t) --> x="lua-5.1.tar.gz"
string.len (s)
""
has length 0.
Embedded zeros are counted,
so "a\000bc\000"
has length 5.
string.lower (s)
string.match (s, pattern [, init])
pattern
in the string s
.
If it finds one, then match
returns
the captures from the pattern;
otherwise it returns nil.
If pattern
specifies no captures,
then the whole match is returned.
A third, optional numerical argument init
specifies
where to start the search;
its default value is 1 and can be negative.
string.rep (s, n)
n
copies of
the string s
.
string.reverse (s)
s
reversed.
string.sub (s, i [, j])
s
that
starts at i
and continues until j
;
i
and j
can 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 string.sub(s,1,j)
returns a prefix of s
with length j
,
and string.sub(s, -i)
returns a suffix of s
with length i
.
string.upper (s)
A character class is used to represent a set of characters. The following combinations are allowed in describing a character class:
^$()%.[]*+-?
)
represents the character x itself.
.
: (a dot) represents all characters.%a
: represents all letters.%c
: represents all control characters.%d
: represents all digits.%l
: represents all lowercase letters.%p
: represents all punctuation characters.%s
: represents all space characters.%u
: represents all uppercase letters.%w
: represents all alphanumeric characters.%x
: represents all hexadecimal digits.%z
: represents the character with representation 0.%x
: (where x is any non-alphanumeric character)
represents the character x.
This is the standard way to escape the magic characters.
Any punctuation character (even the non magic)
can be preceded by a '%
'
when used to represent itself in a pattern.
[set]
:
represents the class which is the union of all
characters in set.
A range of characters can be specified by
separating the end characters of the range with a '-
'.
All classes %
x described above can also be used as
components in set.
All other characters in set represent themselves.
For example, [%w_]
(or [_%w]
)
represents all alphanumeric characters plus the underscore,
[0-7]
represents the octal digits,
and [0-7%l%-]
represents the octal digits plus
the lowercase letters plus the '-
' character.
The interaction between ranges and classes is not defined.
Therefore, patterns like [%a-z]
or [a-%%]
have no meaning.
[^set]
:
represents the complement of set,
where set is interpreted as above.
For all classes represented by single letters (%a
, %c
, etc.),
the corresponding uppercase letter represents the complement of the class.
For instance, %S
represents all non-space characters.
The definitions of letter, space, and other character groups
depend on the current locale.
In particular, the class [a-z]
may not be equivalent to %l
.
A pattern item can be
*
',
which matches 0 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
+
',
which matches 1 or more repetitions of characters in the class.
These repetition items will always match the longest possible sequence;
-
',
which also matches 0 or more repetitions of characters in the class.
Unlike '*
',
these repetition items will always match the shortest possible sequence;
?
',
which matches 0 or 1 occurrence of a character in the class;
%n
, for n between 1 and 9;
such item matches a substring equal to the n-th captured string
(see below);
%bxy
, where x and y are two distinct characters;
such item matches strings that start with x, end with y,
and where the x and y are balanced.
This means that, if one reads the string from left to right,
counting +1 for an x and -1 for a y,
the ending y is the first y where the count reaches 0.
For instance, the item %b()
matches expressions with
balanced parentheses.
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.
A pattern can contain sub-patterns enclosed in parentheses;
they describe captures.
When a match succeeds, the substrings 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.
As a special case, the empty capture ()
captures
the current string position (a number).
For instance, if we apply the pattern "()aa()"
on the
string "flaaap"
, there will be two captures: 3 and 5.
A pattern cannot contain embedded zeros. Use %z
instead.
This library provides generic functions for table manipulation.
It provides all its functions inside the table table
.
Most functions in the table library assume that the table represents an array or a list. For these functions, when we talk about the "length" of a table we mean the result of the length operator.
table.concat (table [, sep [, i [, j]]])
table[i]..sep..table[i+1] ··· sep..table[j]
.
The default value for sep
is the empty string,
the default for i
is 1,
and the default for j
is the length of the table.
If i
is greater than j
, returns the empty string.
table.insert (table, [pos,] value)
Inserts element value
at position pos
in table
,
shifting up other elements to open space, if necessary.
The default value for pos
is n+1
,
where n
is the length of the table (see §2.5.5),
so that a call table.insert(t,x)
inserts x
at the end
of table t
.
table.maxn (table)
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)
table.remove (table [, pos])
Removes from table
the element at position pos
,
shifting down other elements to close the space, if necessary.
Returns the value of the removed element.
The default value for pos
is n
,
where n
is the length of the table,
so that a call table.remove(t)
removes the last element
of table t
.
table.sort (table [, comp])
table[1]
to table[n]
,
where n
is the length of the table.
If comp
is given,
then it must be a function that receives two table elements,
and returns true
when the first is less than the second
(so that 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.
This library is an interface to the standard C math library.
It provides all its functions inside the table math
.
math.abs (x)
Returns the absolute value of x
.
math.acos (x)
Returns the arc cosine of x
(in radians).
math.asin (x)
Returns the arc sine of x
(in radians).
math.atan (x)
Returns the arc tangent of x
(in radians).
math.atan2 (y, x)
Returns the arc tangent of y/x
(in radians),
but uses the signs of both parameters to find the
quadrant of the result.
(It also handles correctly the case of x
being zero.)
math.ceil (x)
Returns the smallest integer larger than or equal to x
.
math.cos (x)
Returns the cosine of x
(assumed to be in radians).
math.cosh (x)
Returns the hyperbolic cosine of x
.
math.deg (x)
Returns the angle x
(given in radians) in degrees.
math.exp (x)
Returns the value ex.
math.floor (x)
Returns the largest integer smaller than or equal to x
.
math.fmod (x, y)
Returns the remainder of the division of x
by y
that rounds the quotient towards zero.
math.frexp (x)
Returns m
and e
such that x = m2e,
e
is an integer and the absolute value of m
is
in the range [0.5, 1)
(or zero when x
is zero).
math.huge
The value HUGE_VAL
,
a value larger than or equal to any other numerical value.
math.ldexp (m, e)
Returns m2e (e
should be an integer).
math.log (x)
Returns the natural logarithm of x
.
math.log10 (x)
Returns the base-10 logarithm of x
.
math.max (x, ···)
Returns the maximum value among its arguments.
math.min (x, ···)
Returns the minimum value among its arguments.
math.modf (x)
Returns two numbers,
the integral part of x
and the fractional part of x
.
math.pi
The value of pi.
math.pow (x, y)
Returns xy.
(You can also use the expression x^y
to compute this value.)
math.rad (x)
Returns the angle x
(given in degrees) in radians.
math.random ([m [, n]])
This function is an interface to the simple
pseudo-random generator function rand
provided by ANSI C.
(No guarantees can be given for its statistical properties.)
When called without arguments,
returns a uniform pseudo-random real number
in the range [0,1).
When called with an integer number m
,
math.random
returns
a uniform pseudo-random integer in the range [1, m].
When called with two integer numbers m
and n
,
math.random
returns a uniform pseudo-random
integer in the range [m, n].
math.randomseed (x)
Sets x
as the "seed"
for the pseudo-random generator:
equal seeds produce equal sequences of numbers.
math.sin (x)
Returns the sine of x
(assumed to be in radians).
math.sinh (x)
Returns the hyp