ehavior similar to the "add" operation.
%
operation.
Behavior similar to the "add" operation,
with the operation
o1 - floor(o1/o2)*o2
as the primitive operation.
^
(exponentiation) operation.
Behavior similar to the "add" operation,
with the function pow
(from the C math library)
as the primitive operation.
-
operation.
function unm_event (op) local o = tonumber(op) if o then -- operand is numeric? return -o -- '-' here is the primitive 'unm' else -- the operand is not numeric. -- Try to get a handler from the operand local h = metatable(op).__unm if h then -- call the handler with the operand return (h(op)) else -- no handler available: default behavior error(···) end end end
..
(concatenation) operation.
function concat_event (op1, op2) if (type(op1) == "string" or type(op1) == "number") and (type(op2) == "string" or type(op2) == "number") then return op1 .. op2 -- primitive string concatenation else local h = getbinhandler(op1, op2, "__concat") if h then return (h(op1, op2)) else error(···) end end end
#
operation.
function len_event (op) if type(op) == "string" then return strlen(op) -- primitive string length elseif type(op) == "table" then return #op -- primitive table length else local h = metatable(op).__len if h then -- call the handler with the operand return (h(op)) else -- no handler available: default behavior error(···) end end end
See §2.5.5 for a description of the length of a table.
==
operation.
The function getcomphandler
defines how Lua chooses a metamethod
for comparison operators.
A metamethod only is selected when both objects
being compared have the same type
and the same metamethod for the selected operation.
function getcomphandler (op1, op2, event) if type(op1) ~= type(op2) then return nil end local mm1 = metatable(op1)[event] local mm2 = metatable(op2)[event] if mm1 == mm2 then return mm1 else return nil end end
The "eq" event is defined as follows:
function eq_event (op1, op2) if type(op1) ~= type(op2) then -- different types? return false -- different objects end if op1 == op2 then -- primitive equal? return true -- objects are equal end -- try metamethod local h = getcomphandler(op1, op2, "__eq") if h then return (h(op1, op2)) else return false end end
a ~= b
is equivalent to not (a == b)
.
<
operation.
function lt_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 < op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 < op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__lt") if h then return (h(op1, op2)) else error(···) end end end
a > b
is equivalent to b < a
.
<=
operation.
function le_event (op1, op2) if type(op1) == "number" and type(op2) == "number" then return op1 <= op2 -- numeric comparison elseif type(op1) == "string" and type(op2) == "string" then return op1 <= op2 -- lexicographic comparison else local h = getcomphandler(op1, op2, "__le") if h then return (h(op1, op2)) else h = getcomphandler(op1, op2, "__lt") if h then return not h(op2, op1) else error(···) end end end end
a >= b
is equivalent to b <= a
.
Note that, in the absence of a "le" metamethod,
Lua tries the "lt", assuming that a <= b
is
equivalent to not (b < a)
.
table[key]
.
function gettable_event (table, key) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then return v end h = metatable(table).__index if h == nil then return nil end else h = metatable(table).__index if h == nil then error(···) end end if type(h) == "function" then return (h(table, key)) -- call the handler else return h[key] -- or repeat operation on it end end
table[key] = value
.
function settable_event (table, key, value) local h if type(table) == "table" then local v = rawget(table, key) if v ~= nil then rawset(table, key, value); return end h = metatable(table).__newindex if h == nil then rawset(table, key, value); return end else h = metatable(table).__newindex if h == nil then error(···) end end if type(h) == "function" then h(table, key,value) -- call the handler else h[key] = value -- or repeat operation on it end end
function function_event (func, ...) if type(func) == "function" then return func(...) -- primitive call else local h = metatable(func).__call if h then return h(func, ...) else error(···) end end end
Besides metatables, objects of types thread, function, and userdata have another table associated with them, called their environment. Like metatables, environments are regular tables and multiple objects can share the same environment.
Threads are created sharing the environment of the creating thread.
Userdata and C functions are created sharing the environment
of the creating C function.
Non-nested Lua functions
(created by loadfile
, loadstring
or load
)
are created sharing the environment of the creating thread.
Nested Lua functions are created sharing the environment of
the creating Lua function.
Environments associated with userdata have no meaning for Lua. It is only a convenience feature for programmers to associate a table to a userdata.
Environments associated with threads are called global environments. They are used as the default environment for threads and non-nested Lua functions created by the thread and can be directly accessed by C code (see §3.3).
The environment associated with a C function can be directly accessed by C code (see §3.3). It is used as the default environment for other C functions and userdata created by the function.
Environments associated with Lua functions are used to resolve all accesses to global variables within the function (see §2.3). They are used as the default environment for nested Lua functions created by the function.
You can change the environment of a Lua function or the
running thread by calling setfenv
.
You can get the environment of a Lua function or the running thread
by calling getfenv
.
To manipulate the environment of other objects
(userdata, C functions, other threads) you must
use the C API.
Lua performs automatic memory management. This means that you have to worry neither about allocating memory for new objects nor about freeing it when the objects are no longer needed. Lua manages memory automatically by running a garbage collector from time to time 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: tables, userdata, functions, threads, strings, 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 (so that 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 step multiplier controls the relative speed of the collector relative to memory allocation. Larger values make the collector more aggressive but also increase the size of each incremental step. Values smaller than 100 make the collector too slow and can result in the collector never finishing a cycle. The default, 200, means that the collector runs at "twice" the speed of memory allocation.
You can change these numbers by calling lua_gc
in C
or collectgarbage
in Lua.
With these functions you can also control
the collector directly (e.g., stop and restart it).
Using the C API, you can set garbage-collector metamethods for userdata (see §2.8). 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).
Garbage userdata with a field __gc
in their metatables are not
collected immediately by the garbage collector.
Instead, Lua puts them in a list.
After the collection,
Lua does the equivalent of the following function
for each userdata in that list:
function gc_event (udata) local h = metatable(udata).__gc if h then h(udata) end end
At the end of each garbage-collection cycle, the finalizers for userdata are called in reverse order of their creation, among those collected in that cycle. That is, the first finalizer to be called is the one associated with the userdata created last in the program. The userdata itself is freed only in the next garbage-collection cycle.
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 this object.
A weak table can have weak keys, weak values, or both.
A table with weak keys allows the collection of its keys,
but prevents the collection of its values.
A table with both weak keys and weak values allows the collection of
both keys and values.
In any case, if either the key or the value is collected,
the whole pair is removed from the table.
The weakness of a table is controlled by the
__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.
After you use a table as a metatable,
you should not change the value of its __mode
field.
Otherwise, the weak behavior of the tables controlled by this
metatable is undefined.
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 with a call to coroutine.create
.
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 execution.
When you first call coroutine.resume
,
passing as its first argument
a thread returned by coroutine.create
,
the coroutine starts its execution,
at the first line of its main function.
Extra arguments passed to coroutine.resume
are passed on
to the coroutine main 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 the first case, coroutine.resume
returns true,
plus any values returned by the coroutine main function.
In case of errors, coroutine.resume
returns false
plus an error message.
A coroutine yields by calling coroutine.yield
.
When a coroutine yields,
the corresponding coroutine.resume
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, coroutine.resume
also returns true,
plus any values passed to coroutine.yield
.
The next time you resume the same coroutine,
it continues its execution from the point where it yielded,
with the call to coroutine.yield
returning any extra
arguments passed to coroutine.resume
.
Like coroutine.create
,
the coroutine.wrap
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 coroutine.resume
.
coroutine.wrap
returns all the values returned by coroutine.resume
,
except the first one (the boolean error code).
Unlike coroutine.resume
,
coroutine.wrap
does not catch errors;
any error is propagated to the caller.
As an example, consider the following code:
function foo (a) print("foo", a) return coroutine.yield(2*a) end co = coroutine.create(function (a,b) print("co-body", a, b) local r = foo(a+1) print("co-body", r) local r, s = coroutine.yield(a+b, a-b) print("co-body", r, s) return b, "end" end) print("main", coroutine.resume(co, 1, 10)) print("main", coroutine.resume(co, "r")) print("main", coroutine.resume(co, "x", "y")) print("main", coroutine.resume(co, "x", "y"))
When you run it, it produces the following output:
co-body 1 10 foo 2 main true 4 co-body r main true 11 -9 co-body x y main true 10 end main false cannot resume dead coroutine
This section describes the C API for Lua, that is,
the set of C functions available to the host program to communicate
with Lua.
All API functions and related types and constants
are declared in the header file lua.h
.
Even when we use the term "function", any facility in the API may be provided as a macro instead. All such macros use each of 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 a proper definition for the macro luai_apicheck
,
in file luaconf.h
.
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.).
Whenever Lua calls C, the called function gets a new stack,
which is independent of previous stacks and of stacks of
C functions that are still active.
This stack initially contains any arguments to the C function
and it is where the C function pushes its results
to be returned to the caller (see lua_CFunction
).
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)
and
index n represents the last element;
index -1 also represents the last element
(that is, the element at the top)
and index -n represents the first element.
We say that an index is valid
if it lies between 1 and the stack top
(that is, if 1 ≤ abs(index) ≤ top
).
When you interact with Lua API,
you are responsible for ensuring consistency.
In particular,
you are responsible for controlling stack overflow.
You can use the function lua_checkstack
to grow the stack size.
Whenever Lua calls C,
it ensures that at least LUA_MINSTACK
stack positions are available.
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.
Most query functions accept as indices any value inside the
available stack space, that is, indices up to the maximum stack size
you have set through lua_checkstack
.
Such indices are called acceptable indices.
More formally, we define an acceptable index
as follows:
(index < 0 && abs(index) <= top) || (index > 0 && index <= stackspace)
Note that 0 is never an acceptable index.
Unless otherwise noted, any function that accepts valid indices can also be called with pseudo-indices, which represent some Lua values that are accessible to C code but which are not in the stack. Pseudo-indices are used to access the thread environment, the function environment, the registry, and the upvalues of a C function (see §3.4).
The thread environment (where global variables live) is
always at pseudo-index LUA_GLOBALSINDEX
.
The environment of the running C function is always
at pseudo-index LUA_ENVIRONINDEX
.
To access and change the value of global variables, you can use regular table operations over an environment table. For instance, to access the value of a global variable, do
lua_getfield(L, LUA_GLOBALSINDEX, varname);
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
(see lua_pushcclosure
).
Whenever a C function is called,
its upvalues are located at specific pseudo-indices.
These pseudo-indices are produced by the macro
lua_upvalueindex
.
The first value associated with a function is at position
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),
produces an acceptable (but invalid) index.
Lua provides a registry,
a pre-defined table that can be used by any C code to
store whatever Lua value it needs to store.
This table is always located at pseudo-index
LUA_REGISTRYINDEX
.
Any C library can store data into this table,
but it should take care to choose keys different from those used
by other libraries, to avoid collisions.
Typically, you should use as key a string containing your library name
or a light userdata with the address of a C object in your code.
The integer keys in the registry are used by the reference mechanism, implemented by the auxiliary library, and therefore should not be used for other purposes.
Internally, Lua uses the C longjmp
facility to handle errors.
(You can also choose to use exceptions if you use C++;
see file luaconf.h
.)
When Lua faces any error
(such as memory allocation errors, type errors, syntax errors,
and runtime errors)
it raises an error;
that is, it does a long jump.
A protected environment uses setjmp
to set a recover point;
any error jumps to the most recent active recover point.
Most functions in the API can throw an error, for instance due to a memory allocation error. The documentation for each function indicates whether it can throw errors.
Inside a C function you can throw an error by calling lua_error
.
Here we list all functions and types from the C API in alphabetical order. Each function has an indicator like this: [-o, +p, x]
The first field, o
,
is how many elements the function pops from the stack.
The second field, p
,
is how many elements the function pushes onto the stack.
(Any function always pushes its results after popping its arguments.)
A field in the form x|y
means the function can push (or pop)
x
or y
elements,
depending on the situation;
an interrogation mark '?
' means that
we cannot know how many elements the function pops/pushes
by looking only at its arguments
(e.g., they may depend on what is on the stack).
The third field, x
,
tells whether the function may throw errors:
'-
' means the function never throws any error;
'm
' means the function may throw an error
only due to not enough memory;
'e
' means the function may throw other kinds of errors;
'v
' means the function may throw an error on purpose.
lua_Alloc
typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
The type of the memory-allocation function used by Lua states.
The allocator function must provide a
functionality similar to realloc
,
but not exactly the same.
Its arguments are
ud
, an opaque pointer passed to lua_newstate
;
ptr
, a pointer to the block being allocated/reallocated/freed;
osize
, the original size of the block;
nsize
, the new size of the block.
ptr
is NULL
if and only if osize
is zero.
When nsize
is zero, the allocator must return NULL
;
if osize
is not zero,
it should free the block pointed to by ptr
.
When nsize
is not zero, the allocator returns NULL
if and only if it cannot fill the request.
When nsize
is not zero and osize
is zero,
the allocator should behave like malloc
.
When nsize
and osize
are not zero,
the allocator behaves like realloc
.
Lua assumes that the allocator never fails when
osize >= nsize
.
Here is a simple implementation for the allocator function.
It is used in the auxiliary library by luaL_newstate
.
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; /* not used */ if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); }
This code assumes
that free(NULL)
has no effect and that
realloc(NULL, size)
is equivalent to malloc(size)
.
ANSI C ensures both behaviors.
lua_atpanic
[-0, +0, -]
lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
Sets a new panic function and returns the old one.
If an error happens outside any protected environment,
Lua calls a panic function
and then calls exit(EXIT_FAILURE)
,
thus exiting the host application.
Your panic function can avoid this exit by
never returning (e.g., doing a long jump).
The panic function can access the error message at the top of the stack.
lua_call
[-(nargs + 1), +nresults, e]
void lua_call (lua_State *L, int nargs, int nresults);
Calls a function.
To call a function you must use the following protocol:
first, the function to be called is pushed onto the stack;
then, the arguments to the function are pushed
in direct order;
that is, the first argument is pushed first.
Finally you call lua_call
;
nargs
is the number of arguments that you pushed onto the stack.
All arguments and the function value are popped from the stack
when the function is called.
The function results are pushed onto the stack when the function returns.
The number of results is adjusted to nresults
,
unless nresults
is LUA_MULTRET
.
In this case, all results from the function are pushed.
Lua takes care that the returned values fit into the stack space.
The function results are pushed onto the stack in direct order
(the first result is pushed first),
so that after the call the last result is on the top of the stack.
Any error inside the called function is propagated upwards
(with a longjmp
).
The following example shows how the host program can do the equivalent to this Lua code:
a = f("how", t.x, 14)
Here it is in C:
lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */ lua_pushstring(L, "how"); /* 1st argument */ lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */ lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */ lua_remove(L, -2); /* remove 't' from the stack */ lua_pushinteger(L, 14); /* 3rd argument */ lua_call(L, 3, 1); /* call 'f' with 3 arguments and 1 result */ lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global 'a' */
Note that the code above is "balanced": at its end, the stack is back to its original configuration. This is considered good programming practice.
lua_CFunction
typedef int (*lua_CFunction) (lua_State *L);
Type for C functions.
In order to communicate properly with Lua,
a C function must use the following protocol,
which defines the way parameters and results are passed:
a C function receives its arguments from Lua in its stack
in direct order (the first argument is pushed first).
So, when the function starts,
lua_gettop(L)
returns the number of arguments received by the function.
The first argument (if any) is at index 1
and its last argument is at index lua_gettop(L)
.
To return values to Lua, a C function just pushes them onto the stack,
in direct order (the first result is pushed first),
and returns the number of results.
Any other value in the stack below the results will be properly
discarded by Lua.
Like a Lua function, a C function called by Lua can also return
many results.
As an example, the following function receives a variable number of numerical arguments and returns their average and sum:
static int foo (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ lua_Number sum = 0; int i; for (i = 1; i <= n; i++) { if (!lua_isnumber(L, i)) { lua_pushstring(L, "incorrect argument"); lua_error(L); } sum += lua_tonumber(L, i); } lua_pushnumber(L, sum/n); /* first result */ lua_pushnumber(L, sum); /* second result */ return 2; /* number of results */ }
lua_checkstack
[-0, +0, m]
int lua_checkstack (lua_State *L, int extra);
Ensures that there are at least extra
free stack slots in the stack.
It returns false if it cannot grow the stack to that size.
This function never shrinks the stack;
if the stack is already larger than the new size,
it is left unchanged.
lua_close
[-0, +0, -]
void lua_close (lua_State *L);
Destroys all objects in the given Lua state (calling the corresponding garbage-collection metamethods, if any) and frees all dynamic memory used by this state. On several platforms, you may not need to call this function, because all resources are naturally released when the host program ends. On the other hand, long-running programs, such as a daemon or a web server, might need to release states as soon as they are not needed, to avoid growing too large.
lua_concat
[-n, +1, e]
void lua_concat (lua_State *L, int n);
Concatenates the n
values at the top of the stack,
pops them, and leaves the result at the top.
If n
is 1, the result is the single value on the stack
(that is, the function does nothing);
if n
is 0, the result is the empty string.
Concatenation is performed following the usual semantics of Lua
(see §2.5.4).
lua_cpcall
[-0, +(0|1), -]
int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
Calls the C function func
in protected mode.
func
starts with only one element in its stack,
a light userdata containing ud
.
In case of errors,
lua_cpcall
returns the same error codes as lua_pcall
,
plus the error object on the top of the stack;
otherwise, it returns zero, and does not change the stack.
All values returned by func
are discarded.
lua_createtable
[-0, +1, m]
void lua_createtable (lua_State *L, int narr, int nrec);
Creates a new empty table and pushes it onto the stack.
The new table has space pre-allocated
for narr
array elements and nrec
non-array elements.
This pre-allocation is useful when you know exactly how many elements
the table will have.
Otherwise you can use the function lua_newtable
.
lua_dump
[-0, +0, m]
int lua_dump (lua_State *L, lua_Writer writer, void *data);
Dumps a function as a binary chunk.
Receives a Lua function on the top of the stack
and produces a binary chunk that,
if loaded again,
results in a function equivalent to the one dumped.
As it produces parts of the chunk,
lua_dump
calls function writer
(see lua_Writer
)
with the given data
to write them.
The value returned is the error code returned by the last call to the writer; 0 means no errors.
This function does not pop the Lua function from the stack.
lua_equal
[-0, +0, e]
int lua_equal (lua_State *L, int index1, int index2);
Returns 1 if the two values in acceptable indices index1
and
index2
are equal,
following the semantics of the Lua ==
operator
(that is, may call metamethods).
Otherwise returns 0.
Also returns 0 if any of the indices is non valid.
lua_error
[-1, +0, v]
int lua_error (lua_State *L);
Generates a Lua error.
The error message (which can actually be a Lua value of any type)
must be on the stack top.
This function does a long jump,
and therefore never returns.
(see luaL_error
).
lua_gc
[-0, +0, e]
int lua_gc (lua_State *L, int what, int data);
Controls the garbage collector.
This function performs several tasks,
according to the value of the parameter what
:
LUA_GCSTOP
:
stops the garbage collector.
LUA_GCRESTART
:
restarts the garbage collector.
LUA_GCCOLLECT
:
performs a full garbage-collection cycle.
LUA_GCCOUNT
:
returns the current amount of memory (in Kbytes) in use by Lua.
LUA_GCCOUNTB
:
returns the remainder of dividing the current amount of bytes of
memory in use by Lua by 1024.
LUA_GCSTEP
:
performs an incremental step of garbage collection.
The step "size" is controlled by data
(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 data
.
The function returns 1 if the step finished a
garbage-collection cycle.
LUA_GCSETPAUSE
:
sets data
as the new value
for the pause of the collector (see §2.10).
The function returns the previous value of the pause.
LUA_GCSETSTEPMUL
:
sets data
as the new value for the step multiplier of
the collector (see §2.10).
The function returns the previous value of the step multiplier.
lua_getallocf
[-0, +0, -]
lua_Alloc lua_getallocf (lua_State *L, void **ud);
Returns the memory-allocation function of a given state.
If ud
is not NULL
, Lua stores in *ud
the
opaque pointer passed to lua_newstate
.
lua_getfenv
[-0, +1, -]
void lua_getfenv (lua_State *L, int index);
Pushes onto the stack the environment table of the value at the given index.
lua_getfield
[-0, +1, e]
void lua_getfield (lua_State *L, int index, const char *k);
Pushes onto the stack the value t[k]
,
where t
is the value at the given valid index.
As in Lua, this function may trigger a metamethod
for the "index" event (see §2.8).
lua_getglobal
[-0, +1, e]
void lua_getglobal (lua_State *L, const char *name);
Pushes onto the stack the value of the global name
.
It is defined as a macro:
#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
lua_getmetatable
[-0, +(0|1), -]
int lua_getmetatable (lua_State *L, int index);
Pushes onto the stack the metatable of the value at the given acceptable index. If the index is not valid, or if the value does not have a metatable, the function returns 0 and pushes nothing on the stack.
lua_gettable
[-1, +1, e]
void lua_gettable (lua_State *L, int index);
Pushes onto the stack the value t[k]
,
where t
is the value at the given valid index
and k
is the value at the top of the stack.
This function pops the key from the stack (putting the resulting value in its place). As in Lua, this function may trigger a metamethod for the "index" event (see §2.8).
lua_gettop
[-0, +0, -]
int lua_gettop (lua_State *L);
Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack (and so 0 means an empty stack).
lua_insert
[-1, +1, -]
void lua_insert (lua_State *L, int index);
Moves the top element into the given valid index, shifting up the elements above this index to open space. Cannot be called with a pseudo-index, because a pseudo-index is not an actual stack position.
lua_Integer
typedef ptrdiff_t lua_Integer;
The type used by the Lua API to represent integral values.
By default it is a ptrdiff_t
,
which is usually the largest signed integral type the machine handles
"comfortably".
lua_isboolean
[-0, +0, -]
int lua_isboolean (lua_State *L, int index);
Returns 1 if the value at the given acceptable index has type boolean, and 0 otherwise.
lua_iscfunction
[-0, +0, -]
int lua_iscfunction (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a C function, and 0 otherwise.
lua_isfunction
[-0, +0, -]
int lua_isfunction (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a function (either C or Lua), and 0 otherwise.
lua_islightuserdata
[-0, +0, -]
int lua_islightuserdata (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a light userdata, and 0 otherwise.
lua_isnil
[-0, +0, -]
int lua_isnil (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is nil, and 0 otherwise.
lua_isnone
[-0, +0, -]
int lua_isnone (lua_State *L, int index);
Returns 1 if the given acceptable index is not valid (that is, it refers to an element outside the current stack), and 0 otherwise.
lua_isnoneornil
[-0, +0, -]
int lua_isnoneornil (lua_State *L, int index);
Returns 1 if the given acceptable index is not valid (that is, it refers to an element outside the current stack) or if the value at this index is nil, and 0 otherwise.
lua_isnumber
[-0, +0, -]
int lua_isnumber (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a number or a string convertible to a number, and 0 otherwise.
lua_isstring
[-0, +0, -]
int lua_isstring (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a string or a number (which is always convertible to a string), and 0 otherwise.
lua_istable
[-0, +0, -]
int lua_istable (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a table, and 0 otherwise.
lua_isthread
[-0, +0, -]
int lua_isthread (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a thread, and 0 otherwise.
lua_isuserdata
[-0, +0, -]
int lua_isuserdata (lua_State *L, int index);
Returns 1 if the value at the given acceptable index is a userdata (either full or light), and 0 otherwise.
lua_lessthan
[-0, +0, e]
int lua_lessthan (lua_State *L, int index1, int index2);
Returns 1 if the value at acceptable index index1
is smaller
than the value at acceptable index index2
,
following the semantics of the Lua <
operator
(that is, may call metamethods).
Otherwise returns 0.
Also returns 0 if any of the indices is non valid.
lua_load
[-0, +1, -]
int lua_load (lua_State *L, lua_Reader reader, void *data, const char *chunkname);
Loads a Lua chunk.
If there are no errors,
lua_load
pushes the compiled chunk as a Lua
function on top of the stack.
Otherwise, it pushes an error message.
The return values of lua_load
are:
LUA_ERRSYNTAX
:
syntax error during pre-compilation;LUA_ERRMEM
:
memory allocation error.This function only loads a chunk; it does not run it.
lua_load
automatically detects whether the chunk is text or binary,
and loads it accordingly (see program luac
).
The lua_load
function uses a user-supplied reader
function
to read the chunk (see lua_Reader
).
The data
argument is an opaque value passed to the reader function.
The chunkname
argument gi