Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
{ a }
means 0 or more a
's, and [ a ]
means an optional a
.
and break do else elseif end false for function if in local nil not or repeat return then true until while
and
is a reserved word, but And
and AND
are
two different, valid names. As a convention, names starting with an underscore
followed by uppercase letters (such as _VERSION
) are reserved for internal
global variables used by Lua.
+ - * / % ^ # == ~= <= >= < > = ( ) { } [ ] ; : , . .. ...
\a
bell
\b
backspace
\f
form feed
\n
newline
\r
carriage return
\t
horizontal tab
\v
vertical tab
\\
backslash
\"
quotation mark (double quote)
\'
apostrophe (single quote)
\ddd
, where ddd
is a sequence of up to three
decimal digits. (Note that if a numerical escape is to be followed by a digit,
it must be expressed using exactly three digits.) Strings in Lua may contain
any 8-bit value, including embedded zeros, which can be specified as \0
.
[[
, an opening long
bracket of level 1 is written as [=[
, and so on.
A closing long bracket is defined similarly; for instance, a closing long
bracket of level 4 is written as ]====]
. A long string starts with an
opening long bracket of any level and ends at the first closing long bracket
of the same level. Literals in this bracketed form may run for several lines,
do not interpret any escape sequences, and ignore long brackets of any other
level. They may contain anything except a closing bracket of the proper level.
a
is coded as 97, newline is coded as 10, and 1
is
coded as 49), the five literals below denote the same string:
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
0x
. Examples of valid numerical constants are
3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
--
) 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.
nil
, boolean
, number
, string
,
function
, userdata
, thread
, and table
. Nil is the type of the value
nil
, whose main property is to be different from any other value; it usually
represents the absence of a useful value. Boolean is the type of the values
false
and true
. Both nil
and false
make a condition false; any other
value makes it true. Number represents real (double-precision floating-point)
numbers. (It is easy to build Lua interpreters that use other internal
representations for numbers, such as single-precision float or long integers;
see file luaconf.h
.) String represents arrays of characters. Lua is 8-bit
clean: strings may contain any 8-bit character, including embedded zeros
(\0
) (see lua-literal).
thread
represents independent threads of execution and it is used to
implement coroutines (see lua-coroutine). Do not confuse Lua threads with
operating-system threads. Lua supports coroutines on all systems, even those
that do not support threads.
table
implements associative arrays, that is, arrays that can be
indexed not only with numbers, but with any value (except nil
). Tables can
be heterogeneous; that is, they can contain values of all types (except
nil
). Tables are the sole data structuring mechanism in Lua; they may be
used to represent ordinary arrays, 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
(see lua-tableconstructor).
nil
). In
particular, because functions are first-class values, table fields may contain
functions. Thus tables may also carry methods (see lua-function-define).
type
returns a string describing the type of a given
value (see lua-type()).
format
function from the string library (see
string.format()).
var ::= Name
nil
.
var ::= prefixexp [ exp ]
prefixexp
) should result in a table value; the second
expression (exp
) identifies a specific entry inside that table. The
expression denoting the table to be indexed has a restricted syntax; see
lua-expressions for details.
var.NAME
is just syntactic sugar for var["NAME"]
:
var ::= prefixexp . Name
getfenv
(see
lua_getfenv()). To replace it, you call setfenv
(see setfenv()).
(You can only manipulate the environment of C functions through the debug
library; see lua-lib-debug.)
x
is equivalent to _env.x
, which in turn is
equivalent to
gettable_event(_env, "x")
_env
is the environment of the running function. (The _env
variable is
not defined in Lua. We use it here only for explanatory purposes.)
t[i]
is equivalent to a
call gettable_event(t,i)
. (See lua-metatable 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.)
chunk ::= {stat [ ; ]}
;;
is not legal.
luac
for
details. Programs in source and compiled forms are interchangeable; Lua
automatically detects the file type and acts accordingly.
block ::= chunk
stat ::= do block end
return
or break
statement
in the middle of another block (see lua-control).
stat ::= varlist1 = explist1 varlist1 ::= var { , var } explist1 ::= exp { , exp }
nil
s as needed. If the list of expressions ends with a function
call, then all values returned by this call enter in the list of values,
before the adjustment (except when the call is enclosed in parentheses; see
lua-expressions).
i = 3
i, a[i] = i+1, 20
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
x
and y
.
t[i] = val
is
equivalent to settable_event(t,i,val)
. (See lua-metatable 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.)
x = val
is equivalent to the
assignment _env.x = val
, which in turn is equivalent to
settable_event(_env, "x", val)
_env
is the environment of the running function. (The _env
variable is
not defined in Lua. We use it here only for explanatory purposes.)
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
for
statement, in two flavors (see lua-for).
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).
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.
return
statement is used to return values from a function or a chunk
(which is just a function). Functions and chunks may return more than one
value, so the syntax for the return
statement is
stat ::=
return
[explist1]
break
statement is used to terminate the execution of a while
, repeat
,
or for
loop, skipping to the next statement after the loop:
stat ::=
break
break
ends the innermost enclosing loop.
return
and break
statements can only be written as the last
statement of a block. If it is really necessary to return
or break
in the
middle of a block, then an explicit inner block can be used, as in the idioms
do return end
and do break end
, because now return
and break
are
the last statements in their (inner) blocks.
for
statement has two forms: one numeric and one generic.
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
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 var = e1, e2, e3 do block end
do
local var, limit, step = tonumber(e1), tonumber(e2), tonumber(e3)
if not ( var and limit and step ) then error() end
while ( step >0 and var <= limit )
or ( step <=0 and var >= limit ) do
block
var = var + step
end
end
var
, limit
and step
are invisible variables. The names are here for
explanatory purposes only.
break
to exit a for
loop.
var
is local to the loop; you cannot use its value
after the for
ends or is broken. If you need this value, assign it to
another variable before breaking or exiting the loop.
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 explist1 do block end namelist ::= Name { , Name }
for
statement like
for
var1, ..., varn
in
explist
do
block
end
do
local f, s, var = explist
while true do
local var1, ..., varn = f(s, var)
var = var1
if var == nil then break end
block
end
end
explist
is evaluated only once. Its results are an iterator function,
a state
, and an initial value for the first iterator variable.
f
, s
, and var
are invisible variables. The names are here for
explanatory purposes only.
break
to exit a for
loop.
var1, ..., varn
are local to the loop; 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.
stat ::= functioncall
stat ::= local namelist [ = explist1 ] namelist ::= Name { , Name }
nil
.
exp ::= prefixexp exp ::= nil | false | true exp ::= Number exp ::= String exp ::= function exp ::= tableconstructor exp ::= ... exp ::= exp binop exp exp ::= unop exp prefixexp ::= var | functioncall | ( exp )
...
), can only be used inside vararg functions;
they are explained in lua-function-define.
not
(see lua-logicalop), and the unary length operator (see lua-length).
f() -- adjusted to 0 results
g(f(), x) -- f() is adjusted to 1 result
g(x, f()) -- g gets x plus all results from f()
a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
a,b = ... -- a gets the first vararg parameter, b gets
-- the second (both a and b may 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()
{f()} -- creates a list with all results from f()
{...} -- creates a list with all vararg parameters
{f(), nil} -- f() is adjusted to 1 result
(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.)
+
(addition),
-
(subtraction), *
(multiplication), /
(division), %
(modulo)
and ^
(exponentiation); and unary -
(negation). If the operands are numbers,
or strings that can be converted to numbers (see lua-coercion), then all
operations have the usual meaning. Exponentiation works for any exponent. For
instance, x^(-0.5)
computes the inverse of the square root of x
. Modulo is
defined as
a % b == a - math.floor(a/b)*b
== ~= < > <= >=
false
or true
.
==
) 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. Numbers and strings are compared in the usual way. Objects
(tables, userdata, threads, and functions) 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 function), this new object is
different from any previously existing object.
"0"==0
evaluates to false
, and t[0]
and
t["0"]
denote different entries in a table.
~=
is exactly the negation of equality (==
).
and or not
false
and nil
as false and anything else as true.
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-cut evaluation, that is, the second operand is
evaluated only if necessary. Here are some examples:
10 or 20 --> 10 10 or error() --> 10 nil or "a" --> "a" nil and 10 --> nil false and error() --> false false and nil --> false false or nil --> nil 10 and 20 --> 20
-->
indicates the result of the preceding expression.)
..
).
If both operands are strings or numbers, then they are converted to strings
according to the rules mentioned in lua-coercion. Otherwise, the
"concat" metamethod is called (see lua-metatable).
#
. The length of a
string is its number of bytes (that is, the usual meaning of string length
when each character is one byte).
t
is defined to be any integer index n
such that t[n]
is
not nil
and t[n+1]
is nil
; moreover, if t[1]
is nil
, n
may be zero. For a
regular array, with non-nil values from 1 to a given n
, its length is exactly
that n
, the index of its last value. If the array has "holes" (that
is, nil
values between other non-nil values), then #t
may be any of the
indices that directly precedes a nil
value (that is, it may consider any
such nil
value as the end of the array).
or and < > <= >= ~= == .. + - * / not # - (unary) ^
..
) and exponentiation (^
) operators are right
associative. All other binary operators are left associative.
tableconstructor ::= { [ fieldlist ] } fieldlist ::= field { fieldsep field } [ fieldsep ] field ::= [ exp ] = exp | Name = exp | exp fieldsep ::= , | ;
[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 numerical integers, starting with 1.
Fields in the other formats do not affect this counting. For example,
a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }
do
local t = {}
t[f(1)] = g
t[1] = "x" -- 1st exp
t[2] = "y" -- 2nd exp
t.x = 1 -- temp["x"] = 1
t[3] = f(x) -- 3rd exp
t[30] = 23
t[4] = 45 -- 4th exp
a = t
end
exp
and the expression is a
function call, then all values returned by the call enter the list
consecutively (see lua-function). To avoid this, enclose the function
call in parentheses (see lua-expressions).
functioncall ::= prefixexp args
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 (see lua-metatable).
functioncall ::= prefixexp : Name args
v:name(
args
)
is syntactic sugar
for v.name(v,
args
)
, except that v
is evaluated only once.
args ::= ( [ explist1 ] ) args ::= tableconstructor args ::= String
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.
(
in a function call. This restriction avoids some ambiguities
in the language. If you write
a = f
(g).x(a)
a = f(g).x(a)
. So, if you want two
statements, you must add a semi-colon between them. If you actually want to
call f
, you must remove the line break before (g)
.
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 function call as argument; 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
function ::= function funcbody funcbody ::= ( [ parlist1 ] ) block end
stat ::= function funcname funcbody stat ::= local function Name funcbody funcname ::= Name { . Name } [ : Name ]
function f ()
body
end
f = function ()
body
end
function t.a.b.c.f ()
body
end
t.a.b.c.f = function ()
body
end
local function f ()
body
end
local f; f = function f ()
body
end
local f = function f ()
body
end
f
.)
function
. When Lua pre-compiles a chunk, all its function bodies are
pre-compiled 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. Different instances of the same function
may refer to different external local variables and may have different
environment tables.
parlist1 ::= namelist [ , ... ] | ...
...
) at the end of its parameter list. A
vararg function does not adjust its argument list; 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 the call is enclosed in parentheses).
function f(a, b) end
function g(a, b, ...) end
function r() return 1,2,3 end
CALL PARAMETERS f(3) a=3, b=nil f(3, 4) a=3, b=4 f(3, 4, 5) a=3, b=4 f(r(), 10) a=1, b=10 f(r()) a=1, b=2 g(3) a=3, b=nil, ... --> (nothing) g(3, 4) a=3, b=4, ... --> (nothing) g(3, 4, 5, 8) a=3, b=4, ... --> 5 8 g(5, r()) a=5, b=1, ... --> 2 3
return
statement (see lua-control).
If control reaches the end of a function without encountering
a return
statement, then the function returns with no results.
self
. Thus, the statement
function t.a.b.c:f (
params
)
body
end
t.a.b.c:f = function (
self
, params
)
body
end
x = 10 -- global variable
do -- new block
local x = x -- new `x`, with value 10
print(x) --> 10
x = x+1
do -- another block
local x = x+1 -- another `x`
print(x) --> 12
end
print(x) --> 11
end
print(x) --> 10 (the global one)
local x = x
, the new x
being declared is
not in scope yet, and so the second x
refers to the outside variable.
a = {}
local x = 20
for i=1,10 do
local y = 0
a[i] = function () y=y+1; return x+y end
end
y
variable, while all of
them share the same x
.
error
function (see
error()). If you need to catch errors in Lua, you can use the pcall
function (see pcall()).
"__add"
in its metatable. If it finds one, Lua calls that function
to perform the addition.
getmetatable
function
(see getmetatable()).
setmetatable
function (see
setmetatable()). You cannot change the metatable of other types from Lua
(except using the debug library); you must use the C API for that.
__
; for instance, the key for operation "add"
is the string "__add". The semantics of these operations is better explained
by a Lua function describing how the interpreter executes that operation.
rawget
, tonumber
, etc.) are
described in lua-lib-core. In particular, to retrieve the metamethod of a
given object, we use the expression
metatable(obj)[event]
rawget(metatable(obj) or {}, event)
nil
).
getbinhandler
below defines how Lua chooses a handler for a
binary operation. First, Lua tries the first operand. If its type does not
define a handler for the operation, then Lua tries the second operand.
function getbinhandler (op1, op2, event)
return metatable(op1)[event] or metatable(op2)[event]
end
op1 + op2
is
function add_event (op1, op2)
local o1, o2 = tonumber(op1), tonumber(op2)
if o1 and o2 then -- both operands are numeric?
return o1 + o2 -- `+` here is the primitive `add`
else -- at least one of the operands is not numeric
local h = getbinhandler(op1, op2, "__add")
if h then
-- call the handler with both operands
return h(op1, op2)
else -- no handler available: default behavior
error(...)
end
end
end
%
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
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
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
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
return h(table, key,value) -- call the handler
else h[key] = value -- or repeat operation on it
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
setfenv
. You can get the environment of a Lua function or the
running thread by calling getfenv
(see lua_getfenv()). To manipulate the
environment of other objects (userdata, C functions, other threads) you must
use the C API.
lua_gc
(see lua_gc()) in C or
collectgarbage
(see collectgarbage()) in Lua. Both get percentage points
as arguments (so an argument of 100 means a real value of 1). With these
functions you can also control the collector directly (e.g., stop and restart
it).
__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
__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.
__mode
. Otherwise, the weak behavior of the tables controlled by this
metatable is undefined.
coroutine.create
(see
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.
coroutine.resume
(see coroutine.resume()),
passing as its first argument the 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
.
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.
coroutine.yield
(see
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
.
coroutine.create
, the coroutine.wrap
function (see
coroutine.wrap()) 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.
function foo1 (a)
print("foo", a)
return coroutine.yield(2*a)
end
co = coroutine.create(function (a,b)
print("co-body", a, b)
local r = foo1(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"))
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
lua.h
.
macro
instead. All such macros use each of its arguments exactly once
(except for the first argument, which is always a Lua state), and so do not
generate hidden side-effects.
luai_apicheck
,in file
luaconf.h
.
nil
, number, string, etc.).
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
).
lua_checkstack
to grow the stack size (see
lua_checkstack()).
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.
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)
LUA_GLOBALSINDEX
. The environment of the running C function is always at
pseudo-index LUA_ENVIRONINDEX
.
lua_getfield(L, LUA_GLOBALSINDEX, varname);
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,
produces an acceptable (but invalid) 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.
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.
lua_newstate
, lua_close
, lua_load
, lua_pcall
, and lua_cpcall
(see
lua_newstate(), lua_close(), lua_load(),
lua_pcall(), and lua_cpcall()).
lua_error
(see
lua_error()).
realloc
,
but not exactly the same. Its arguments are ud
, an opaque pointer
passed to lua_newstate
(see 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 whenosize >=
nsize`.
luaL_newstate
(see
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);
}
free(NULL)
has no effect and that
realloc(NULL, size)
is equivalent to malloc(size)
. ANSI C ensures both
behaviors.
panic
function
and then calls exit(EXIT_FAILURE)
, thus exiting
the host application. Your panic function may avoid this exit by never
returning (e.g., doing a long jump).
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.
longjmp
).
a = f("how", t.x, 14)
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'
lua_gettop(L)
(see lua_gettop()) 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.
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 */
}
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.
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
string on the stack (that is, the function does nothing); if n
is 0,
the result is the empty string. Concatenation is done following the
usual semantics of Lua (see lua-concat).
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
(see
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.
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
(see lua_newtable()).
lua_dump
calls function writer
(see
lua_Writer) with the given data
to write them.
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.
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
/100 as the new value for the
pause
of the collector (see lua-gc).
The function returns the previous value of the
pause.
LUA_GCSETSTEPMUL
sets data
/100 as the new value for the
step
multiplier
of the collector (see
lua-gc). The function returns the
previous value of the step multiplier.
ud
is
not NULL
, Lua stores in *ud
the opaque pointer passed to
lua_newstate
(see lua_newstate()).
t[k]
, where t
is the value at the
given valid index index
. As in Lua, this function may trigger a
metamethod for the "index" event (see lua-metatable).
name
. It is defined as
a macro:
#define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, s)
t[k]
, where t
is the value at the
given valid index index
and k
is the value at the top of the
stack.
ptrdiff_t
, which is usually the largest integral
type the machine handles "comfortably".
nil
, and 0
otherwise.
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.
int lua_load (lua_State *L,
lua_Reader reader,
void *data,
const char *chunkname);
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:
0
: no errors;
LUA_ERRSYNTAX
: syntax error during pre-compilation;
LUA_ERRMEM
: memory allocation error.
lua_load
automatically detects whether the chunk is text or binary,
and loads it accordingly (see program luac
).
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.
chunkname
argument gives a name to the chunk, which is used for
error messages and in debug information (see lua-apiDebug).
NULL
if cannot create the
state (due to lack of memory). The argument f
is the allocator
function; Lua does all memory allocation for this state through this
function. The second argument, ud
, is an opaque pointer that Lua
simply passes to the allocator in every call.
lua_createtable(L, 0, 0)
(see
lua_createtable()).
lua_State
(see lua_State) that represents this new
thread. The new state returned by this function shares with the
original state all global objects (such as tables), but has an
independent execution stack.
gc
metamethod, Lua calls
the metamethod and marks the userdata as finalized. When this userdata
is collected again then Lua frees its corresponding memory.
lua_next
returns 0 (and pushes
nothing).
/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}
lua_tolstring
(see
lua_tolstring()) directly on a key, unless you know that the
key is actually a string. Recall that lua_tolstring
changes
the
value at the given index; this confuses the next call to lua_next
.
luaconf.h
.
#
); for userdata, this is the size of the
block of memory allocated for the userdata; for other values, it is 0.
nargs
and nresults
have the same meaning as in lua_call
(see lua_call()). If there are no errors during the call,
lua_pcall
behaves exactly like lua_call
. However, if there is any
error, lua_pcall
catches it, pushes a single value on the stack (the
error message), and returns an error code. Like lua_call
,
lua_pcall
always removes the function and its arguments from the
stack.
errfunc
is 0, then the error message returned on the stack is
exactly the original error message. Otherwise, errfunc
is the stack
index of an error
handler function
. (In the current
implementation, this index cannot be a pseudo-index.) In case of
runtime errors, this function will be called with the error message
and its return value will be the message returned on the stack by
lua_pcall
.
lua_pcall
, since
by then the stack has unwound.
lua_pcall
function returns 0 in case of success or one of the
following error codes (defined in lua.h
):
LUA_ERRRUN
a runtime error.
LUA_ERRMEM
memory allocation error. For such errors, Lua does
not call the error handler function.
LUA_ERRERR
error while running the error handler function.
n
elements from the stack.
b
onto the stack.
lua_pushcclosure
is called to create and push
the C function onto the stack, with the argument n
telling how many
values should be associated with the function. lua_pushcclosure
also
pops these values from the stack.
function
that, when called, invokes the corresponding C function.
lua_pushcfunction
is defined as a macro:
#define lua_pushcfunction(L,f) lua_pushcclosure(L,f,0)
sprintf
, but has some
important differences:
%%
(inserts a %
in the string), %s
(inserts a zero-terminated
string, with no size restrictions), %f
(inserts a
lua_Number
), %p
(inserts a pointer as a hexadecimal numeral),
%d
(inserts an int
), and %c
(inserts an int
as a
character).
n
onto the stack.
s
with size len
onto the stack.
Lua makes (or reuses) an internal copy of the given string, so the
memory at s
can be freed or reused immediately after the function
returns. The string can contain embedded zeros.
n
onto the stack.
s
onto the stack.
Lua makes (or reuses) an internal copy of the given string, so the
memory at s
can be freed or reused immediately after the function
returns. The string cannot contain embedded zeros; it is assumed to
end at the first zero.
L
onto the stack. Returns 1 if this
thread is the main thread of its state.
const char *lua_pushvfstring (lua_State *L,
const char *fmt,
va_list argp);
lua_pushfstring
(see lua_pushfstring()), except
that it receives a va_list
instead of a variable number of
arguments.
index1
and
index2
are primitively equal (that is, without calling metamethods).
Otherwise returns 0. Also returns 0 if any of the indices are non
valid.
lua_gettable
(see lua_gettable()), but does a raw
access (i.e., without metamethods).
t[n]
, where t
is the value at the
given valid index index
. The access is raw; that is, it does not
invoke metamethods.
lua_settable
(see lua_settable()), but does a raw
assignment (i.e., without metamethods).
t[n] = v
, where t
is the value at the given
valid index index
and v
is the value at the top of the stack.
lua_load
(see lua_load()). Every
time it needs another piece of the chunk, lua_load
calls the reader,
passing along its data
parameter. The reader must return a pointer
to a block of memory with a new piece of the chunk and set size
to
the block size. The block must exist until the reader function is
called again. To signal the end of the chunk, the reader must return
NULL
. The reader function may return pieces of any size greater than
zero.
f
as the new value of global name
. It is
defined as a macro:
#define lua_register(L,n,f) \
(lua_pushcfunction(L, f), lua_setglobal(L, n))
lua_resume
(see
lua_resume()) with narg
being the number of arguments. This
call returns when the coroutine suspends or finishes its execution.
When it returns, the stack contains all values passed to lua_yield
(see lua_yield()), or all values returned by the body function.
lua_resume
returns LUA_YIELD
if the coroutine yields, 0 if the
coroutine finishes its execution without errors, or an error code in
case of errors (see lua_pcall()). In case of errors, the stack
is not unwound, so you can use the debug API over it. The error
message is on the top of the stack. To restart a coroutine, you put on
its stack only the values to be passed as results from lua_yield
,
and then call lua_resume
.
f
with user data
ud
.
lua_setfenv
returns 0.
Otherwise it returns 1.
t[k] = v
, where t
is the value at the given
valid index index
and v
is the value at the top of the stack.
name
. It is defined as a macro:
#define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, s)
t[k] = v
, where t
is the value at the given
valid index index
, v
is the value at the top of the stack, and k
is the value just below the top.
nil
. If index
is 0, then all stack
elements are removed.
lua_newstate
(see
lua_newstate()), which creates a Lua state from scratch.
L
.
LUA_YIELD
if the thread is
suspended.
lua_toboolean
returns 1 for
any Lua value different from false
and nil
; otherwise it returns
0. It also returns 0 when called with a non-valid index. (If you want
to accept only actual boolean values, use lua_isboolean
lua_isboolean() to test the value's type.)
NULL
.
lua_Integer
(see lua_Integer). The Lua value
must be a number or a string convertible to a number (see
lua-coercion); otherwise, lua_tointeger
returns 0.
len
is not NULL
, it also sets *len
with the string length. The
Lua value must be a string or a number; otherwise, the function
returns NULL
. If the value is a number, then lua_tolstring
also
changes the actual value in the stack to a
string
. (This change
confuses lua_next
lua_next() when lua_tolstring
is applied
to keys during a table traversal.)
lua_tolstring
returns a fully aligned pointer to a string inside the
Lua state. This string always has a zero (\0
) after its last
character (as in C), but may contain other zeros in its body. Because
Lua has garbage collection, there is no guarantee that the pointer
returned by lua_tolstring
will be valid after the corresponding
value is removed from the stack.
lua_Number
(see lua_Number). The Lua value must be a number
or a string convertible to a number (see lua-coercion);
otherwise, lua_tonumber
returns 0.
void*
). The value may be a userdata, a table, a thread, or
a function; otherwise, lua_topointer
returns NULL
. Different
objects will give different pointers. There is no way to convert the
pointer back to its original value.
lua_State*
lua_State). This value must be a
thread; otherwise, the function returns NULL
.
NULL
.
LUA_TNONE
for a non-valid index (that is, an index to an "empty"
stack position). The types returned by lua_type
are coded by the
following constants defined in lua.h
: LUA_TNIL
, LUA_TNUMBER
,
LUA_TBOOLEAN
, LUA_TSTRING
, LUA_TTABLE
, LUA_TFUNCTION
,
LUA_TUSERDATA
, LUA_TTHREAD
, and LUA_TLIGHTUSERDATA
.
tp
, which must be
one the values returned by lua_type
.
lua_dump
(see lua_dump()). Every
time it produces another piece of chunk, lua_dump
calls the writer,
passing along the buffer to be written (p
), its size (sz
), and the
data
parameter supplied to lua_dump
.
lua_dump
from calling the writer again.
same
global state.
n
values from the stack from
, and pushes them
onto the stack to
.
return lua_yield (L, nresults);
lua_yield
in that way, the running coroutine
suspends its execution, and the call to lua_resume
(see
lua_resume()) that started this coroutine returns. The
parameter nresults
is the number of values from the stack that are
passed as results to lua_resume
.
10 20 30 40 50*
(from bottom to top; the *
marks the top), then
lua_pushvalue(L, 3) --> 10 20 30 40 50 30* lua_pushvalue(L, -1) --> 10 20 30 40 50 30 30* lua_remove(L, -3) --> 10 20 30 40 30 30* lua_remove(L, 6) --> 10 20 30 40 30* lua_insert(L, 1) --> 30 10 20 30 40* lua_insert(L, -1) --> 30 10 20 30 40* (no effect) lua_replace(L, 2) --> 30 40 20 30* lua_settop(L, -3) --> 30 40* lua_settop(L, 6) --> 30 40 nil nil nil nil*
typedef struct lua_Debug {
int event;
const char *name; /* (n) */
const char *namewhat; /* (n) */
const char *what; /* (S) */
const char *source; /* (S) */
int currentline; /* (l) */
int nups; /* (u) number of upvalues */
int linedefined; /* (S) */
int lastlinedefined; /* (S) */
char short_src[LUA_IDSIZE]; /* (S) */
/* private part */
other fields
} lua_Debug;
lua_getstack
(see lua_getstack()) fills only the private part
of this structure, for later use. To fill the other fields of lua_Debug
with
useful information, call lua_getinfo
(see lua_getinfo()).
lua_Debug
have the following meaning:
source
If the function was defined in a string, then source
is
that string. If the function was defined in a file, then
source
starts with a @
followed by the file name.
short_src
a "printable" version of source
, to be used in error messages.
linedefined
the line number where the definition of the function starts.
lastlinedefined
the line number where the definition of the function ends.
what
the string "Lua"
if the function is a Lua function,
"C"
if it is a C function, "main"
if it is the main
part of a chunk, and "tail"
if it was a function that
did a tail call. In the latter case, Lua has no other
information about the function.
currentline
the current line where the given function is executing.
When no line information is available, currentline
is
set to -1.
name
a reasonable name for the given function. Because
functions in Lua are first-class values, they do not have
a fixed name: some functions may be the value of multiple
global variables, while others may be stored only in a
table field. The lua_getinfo
function checks how the
function was called to find a suitable name. If it cannot
find a name, then name
is set to NULL
.
namewhat
explains the name
field. The value of namewhat
can be
"global"
, "local"
, "method"
, "field"
,
"upvalue"
, or ""
(the empty string), according to how
the function was called. (Lua uses the empty string when
no other option seems to apply.) nups
the number of
upvalues of the function.
ar
must be a valid activation record that was filled by a previous call
to lua_getstack
(see lua_getstack()) or given as argument to
a hook (see lua_Hook).
what
string with the character >
. (In that case,
lua_getinfo
pops the function in the top of the stack.) For
instance, to know in which line a function f
was defined, you can
write the following code:
lua_Debug ar;
lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* get global 'f' */
lua_getinfo(L, ">S", &ar);
printf("%d\n", ar.linedefined);
what
selects some fields of the
structure ar
to be filled or a value to be pushed on the stack:
'n'
fills in the field name
and namewhat
'S'
fills in the fields source
, short_src
, linedefined
,
lastlinedefined
, and what
'l'
fills in the field currentline
'u'
fills in the field nups
'f'
pushes onto the stack the function that is running at the
given level
'L'
pushes onto the stack a table whose indices are the numbers
of the lines that are valid on the function. (A valid line
is a
line with some associated code, that is, a line where you can put
a break point. Non-valid lines include empty lines and comments.)
what
).
ar
must be a valid activation record that was filled
by a previous call to lua_getstack
(see lua_getstack()) or
given as argument to a hook (see lua_Hook). The index n
selects which local variable to inspect (1 is the first parameter or
active local variable, and so on, until the last active local
variable). lua_getlocal
pushes the variable's value onto the stack
and returns its name.
(
(open parentheses) represent
internal variables (loop control variables, temporaries, and C
function locals).
NULL
(and pushes nothing) when the index is greater than the
number of active local variables.
lua_Debug
(see lua_Debug)
structure with an identification of the activation record
of the
function executing at a given level. Level 0 is the current running
function, whereas level n+1
is the function that has called level
n
. When there are no errors, lua_getstack
returns 1; when called
with a level greater than the stack depth, it returns 0.
lua_getupvalue
gets
the index n
of an upvalue, pushes the upvalue's value onto the
stack, and returns its name. funcindex
points to the closure in the
stack. (Upvalues have no particular order, as they are active through
the whole function. So, they are numbered in an arbitrary order.)
NULL
(and pushes nothing) when the index is greater than the
number of upvalues. For C functions, this function uses the empty
string ""
as a name for all upvalues.
ar
argument has its field event
set
to the specific event that triggered the hook. Lua identifies these
events with the following constants: LUA_HOOKCALL
, LUA_HOOKRET
,
LUA_HOOKTAILRET
, LUA_HOOKLINE
, and LUA_HOOKCOUNT
. Moreover, for
line events, the field currentline
is also set. To get the value of
any other field in ar
, the hook must call lua_getinfo
(see
lua_getinfo()). For return events, event
may be
LUA_HOOKRET
, the normal value, or LUA_HOOKTAILRET
. In the latter
case, Lua is simulating a return from a function that did a tail call;
in this case, it is useless to call lua_getinfo
.
f
is the hook function. mask
specifies on which events
the hook will be called: it is formed by a bitwise or
of the
constants LUA_MASKCALL
, LUA_MASKRET
, LUA_MASKLINE
, and
LUA_MASKCOUNT
. The count
argument is only meaningful when the mask
includes LUA_MASKCOUNT
. For each event, the hook is called as
explained below:
The call 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.
The return hook
: is called when the interpreter returns from a
function. The hook is called just before Lua leaves the function.
You have no access to the values to be returned by the function.
The line hook
: is called when the interpreter is about to start
the execution of a new line of code, or when it jumps back in the
code (even to the same line). (This event only happens while Lua is
executing a Lua function.)
The count hook
: is called after the interpreter executes every
count
instructions. (This event only happens while Lua is
executing a Lua function.)
mask
to zero.
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.
NULL
(and pops nothing) when the index is greater than the
number of active local variables.
funcindex
and n
are as in the
lua_getupvalue
(see lua_getupvalue()).
NULL
(and pops nothing) when the index is greater than the
number of upvalues.
int listvars (lua_State *L, int level) {
lua_Debug ar;
int i;
const char *name;
if (lua_getstack(L, level, &ar) == 0)
return 0; /* failure: no such level in the stack */
i = 1;
while ((name = lua_getlocal(L, &ar, i++)) != NULL) {
printf("local %d %s\n", i-1, name);
lua_pop(L, 1); /* remove variable value */
}
lua_getinfo(L, "f", &ar); /* retrieves function */
i = 1;
while ((name = lua_getupvalue(L, -1, i++)) != NULL) {
printf("upvalue %d %s\n", i-1, name);
lua_pop(L, 1); /* remove upvalue value */
}
return 1;
}
lauxlib.h
and have a prefix luaL_
.
luaL_check*
or luaL_opt*
. All of these
functions raise 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.
s
with length l
to the buffer B
(see luaL_Buffer). The string may contain embedded zeros.
B
(see luaL_Buffer) a string of length
n
previously copied to the buffer area (see
luaL_prepbuffer()).
s
to the buffer B
(see luaL_Buffer). The string may not contain embedded zeros.
B
(see
luaL_Buffer). Pops the value.
void luaL_argcheck (lua_State *L,
int cond,
int narg,
const char *extramsg);
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>)
func
is retrieved
from the call stack:
bad argument #<narg> to <func> (<extramsg>)
return luaL_argerror(
args
)
.
string buffer
.
b
of type luaL_Buffer
.
luaL_buffinit(L, &b)
(see
luaL_buffinit()).
luaL_add*
functions.
luaL_pushresult(&b)
(see
luaL_pushresult()). This call leaves the final string on the
top of the stack.
luaL_addvalue
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.
B
. This function does not allocate any space;
the buffer must be declared as a variable (see luaL_Buffer).
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).
nil
) at position narg
.
narg
is a number and returns
this number cast to an int
.
narg
is a number and returns
this number cast to a lua_Integer
(see lua_Integer).
narg
is a number and returns
this number cast to a long
.
const char *luaL_checklstring (lua_State *L, int narg, size_t *l);
narg
is a string and returns
this string; if l
is not NULL
fills *l
with the string's length.
narg
is a number and returns
this number (see lua_Number).
int luaL_checkoption (lua_State *L,
int narg,
const char *def,
const char *const lst[]);
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.
def
is not NULL
, the function uses def
as a default value
when there is no argument narg
or if this argument is nil
.
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.
narg
is a string and returns
this string.
void *luaL_checkudata (lua_State *L, int narg, const char *tname);
narg
is a userdata of the type
tname
(see luaL_newmetatable()).
(luaL_loadfile(L, filename) || lua_pcall(L, 0, LUA_MULTRET, 0))
(luaL_loadstring(L, str) || lua_pcall(L, 0, LUA_MULTRET, 0))
fmt
plus any
extra arguments, following the same rules of lua_pushfstring
(see
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.
return luaL_error(
args
)
.
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.
tname
in
the registry (see luaL_newmetatable()).
const char *luaL_gsub (lua_State *L,
const char *s,
const char *p,
const char *r);
s
by replacing any occurrence of the string
p
with the string r
. Pushes the resulting string on the stack and
returns it.
int luaL_loadbuffer (lua_State *L,
const char *buff,
size_t sz,
const char *name);
lua_load
(see
lua_load()) to load the chunk in the buffer pointed to by
buff
with size sz
.
lua_load
. name
is the
chunk name, used for debug information and error messages.
lua_load
(see
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 #
.
lua_load
, but it has an
extra error code LUA_ERRFILE
if it cannot open/read the file.
lua_load
, this function only loads the chunk; it does not run it.
lua_load
(see
lua_load()) to load the chunk in the zero-terminated string
s
.
lua_load
.
lua_load
, this function only loads the chunk; it does not
run it.
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.
tname
in the registry.
lua_newstate
(see
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.
NULL
if there is a memory allocation
error.
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.
lua_Integer luaL_optinteger (lua_State *L,
int narg,
lua_Integer d);
narg
is a number, returns this number cast
to a lua_Integer
(see lua_Integer). If this argument is
absent or is nil
, returns d
. Otherwise, raises an error.
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.
const char *luaL_optlstring (lua_State *L,
int narg,
const char *d,
size_t *l);
narg
is a string, returns this string. If
this argument is absent or is nil
, returns d
. Otherwise, raises an
error.
l
is not NULL
, fills the position *l
with the results' length.
narg
is a number, returns this number. If
this argument is absent or is nil
, returns d
. Otherwise, raises an
error.
narg
is a string, returns this string. If
this argument is absent or is nil
, returns d
. Otherwise, raises an
error.
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
(see luaL_addsize()) with the size of the string to actually
add it to the buffer.
B
leaving the final string on the top of
the stack.
reference
, in the table at index t
, for the
object at the top of the stack (and pops the object).
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)
(see lua_rawgeti()).
Function luaL_unref
(see luaL_unref()) frees a reference and
its associated object.
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_register
(see
luaL_register()). name
is the function name and func
is a
pointer to the function. Any array of luaL_Reg
must end with a
sentinel entry in which both name
and func
are NULL
.
void luaL_register (lua_State *L,
const char *libname,
const luaL_Reg *l);
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.
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.
idx
.
location
: bad argument
narg
to
'func'
(
tname
expected, got
rt
)
location
is produced by luaL_where
(see
luaL_where()), func
is the name of the current function, and
rt
is the type name of the actual argument.
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.
ref
is LUA_NOREF
or LUA_REFNIL
, luaL_unref
does nothing.
lvl
in the call stack. Typically this string has
the following format:
chunkname:currentline:
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., sort
).
luaL_openlibs
function, which opens all standard libraries (see
luaL_openlibs()). Alternatively, the host program can open the libraries
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 and the Operating System
libraries), 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
(see lua_call()).
{v}
[, {message}
]) assert()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!"
{opt}
[, {arg}
]) collectgarbage(){opt}
:
"stop"
stops the garbage collector.
"restart"
restarts the garbage collector.
"collect"
performs a full garbage-collection cycle.
"count"
returns the total memory in use by Lua (in Kbytes).
"step"
performs a garbage-collection step. The step "size" is
controlled by {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.
"setpause"
sets {arg}
/100 as the new value for the pause
of
the collector (see lua-gc).
"setstepmul"
sets {arg}
/100 as the new value for thestep
multiplier` of the collector (see lua-gc).
{filename}
) dofile()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).
{message}
[, {level}
]) error()message
as
the error message. Function {error}
never returns.
{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
). Lua itself does not use this variable;
changing its value does not affect any environment, nor vice-versa.
(Use setfenv
to change environments.)
{f}
) getfenv(){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.
{object}
) getmetatable(){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.
{t}
) ipairs(){t}
, and 0, so
that the construction
for i,v in ipairs(t) do
body
end
1,t[1]
), (2,t[2]
), ..., up to the
first integer key absent from the table.
{func}
[, {chunkname}
]) load(){func}
to get its pieces. Each call to
{func}
must return a string that concatenates with previous results. A
return of nil
(or no value) signals the end of the chunk.
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.
{filename}
]) loadfile()load
(see load()), but gets the chunk from file
{filename}
or from the standard input, if no file name is given.
{string}
[, {chunkname}
]) loadstring()load
(see load()), but gets the chunk from the
given {string}
.
assert(loadstring(s))()
{table}
[, {index}
]) next()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.
for
or the ipairs() function.)
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.
{t}
) pairs(){t}
, and nil
,
so that the construction
for k,v in pairs(t) do
body
end
{t}
.
{f}
, {arg1}
, {...}
) pcall(){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
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
(see string.format()).
{v1}
, {v2}
) rawequal(){v1}
is equal to {v2}
, without invoking any metamethod.
Returns a boolean.
{table}
, {index}
) rawget()table[index]
, without invoking any
metamethod. {table}
must be a table; {index}
may be any value.
{table}
, {index}
, {value}
) rawset()table[index]
to {value}
, without invoking any
metamethod. {table}
must be a table, {index}
any value different from
nil
, and {value}
any Lua value.
{table}
.
{index}
, {...}
) select(){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.
{f}
, {table}
) setfenv(){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.
{f}
is 0 setfenv
changes the environment of
the running thread. In this case, setfenv
returns no values.
{table}
, {metatable}
) setmetatable(){metatable}
is
nil
, removes the metatable of the given table. If the original
metatable has a "__metatable"
field, raises an error.
{table}
.
{e}
[, {base}
]) tonumber()tonumber
returns
this number; otherwise, it returns nil
.
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 may have a decimal part, as well as an
optional exponent part (see lua-lexical). In other bases,
only unsigned integers are accepted.
{e}
) tostring()string.format
(see string.format()).
{e}
has a "__tostring"
field, tostring
calls
the corresponding value with {e}
as argument, and uses the result of
the call as its result.
{v}
) lua-type()"nil"
(a string, not the value nil
),
"number"
, "string"
, "boolean
, "table"
, "function"
,
"thread"
, and "userdata"
.
{list}
[, {i}
[, {j}
]]) unpack()return list[i], list[i+1], ..., list[j]
{i}
is 1 and {j}
is the length of the list, as
defined by the length operator (see lua-length).
"Lua 5.1"
.
{f}
, {err}
) xpcall()pcall
(see 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}
.
coroutine
. See lua-coroutine for a
general description of coroutines.
{f}
) coroutine.create(){f}
. {f}
must be a Lua function.
Returns this new coroutine, an object with type "thread"
.
{co}
[, {val1}
, {...}
]) coroutine.resume(){co}
. The first time
you resume a coroutine, it starts running its body. The values {val1}
,
{...}
are passed as arguments to the body function. If the coroutine has
yielded, resume
restarts it; the values {val1}
, {...}
are passed as
the results from the yield.
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.
nil
when called by the main
thread.
{co}
) coroutine.status(){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.
{f}
) coroutine.wrap(){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()yield
are passed as extra results to resume
.
require
and module
(see require() and module()). Everything else is
exported in a table package
.
{name}
[, {...}
]) module()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
.
{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
.
options
after the module name,
where each option is a function to be applied over the module.
{modname}
) require()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.
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 below).
require
first uses a dynamic link facility
to link the application with the library. Then it tries to find a C
function inside this 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
.
require
finds neither a Lua library nor a C library for a module,
it calls the all-in-one loader
. This loader 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.
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]
.
require
signals an error.
package.cpath
in the same way it
initializes the Lua path package.path
, using the environment
variable LUA_CPATH
(plus another default path defined in
luaconf.h
).
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.
{libname}
, {funcname}
) package.loadlib(){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)).
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).
dlfcn
standard).
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.
templates
separated by semicolons. For each
template, require
will change each interrogation mark in the
template by filename
, which is modname
with each dot replaced by a
"directory separator" (such as "/"
in Unix); then it will try to
load the resulting file name. So, for instance, if the Lua path is
"./?.lua;./?.lc;/usr/local/?/init.lua"
foo
will try to load the
files ./foo.lua
, ./foo.lc
, and /usr/local/foo/init.lua
, in that
order.
{module}
) package.seeall(){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}
.
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)
.
{s}
[, {i}
[, {j}
]]) string.byte()s[i]
,
s[i+1]
,..., s[j]
. The default value for {i}
is 1; the default
value for {j}
is {i}
.
{...}
) string.char(){function}
) string.dump(){function}
must be a Lua function without
upvalues.
{s}
, {pattern}
[, {init}
[, {plain}
]]) string.find(){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 may 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.
{formatstring}
, {...}
) string.format()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')
"a string with \"quotes\" and \
new line"
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.
{s}
, {pattern}
) string.gmatch(){pattern}
over string {s}
.
{pattern}
specifies no captures, then the whole match is produced
in each call.
s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
{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
{s}
, {pattern}
, {repl}
[, {n}
]) string.gsub(){s}
in which all occurrences of the {pattern}
have
been replaced by a replacement string specified by {repl}
, which may
be a string, a table, or a function. gsub
also returns, as its
second value, the total number of substitutions made.
{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 %
.
{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.
{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.
false
or nil
, then there is no replacement
(that is, the original match is kept in the string).
{n}
limits the maximum number of
substitutions to occur. For instance, when {n}
is 1 only the first
occurrence of pattern
is replaced.
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"
{s}
) string.len()""
has
length 0. Embedded zeros are counted, so "a\000b\000c"
has length 5.
{s}
) string.lower(){s}
, {pattern}
[, {init}
]) string.match()match
of {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
may be negative.
{s}
, {n}
) string.rep(){n}
copies of the string
{s}
.
{s}
, {i}
[, {j}
]) string.sub(){s}
that starts at {i}
and continues until
{j}
; {i}
and {j}
may be negative. If {j}
is absent, then it is assumed
to be equal to -1
(which is the same as the string length). In
particular, the call 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}
.
{s}
) string.upper()x
(where x
is not one of the magic characters ^$()%.[]*+-?
)
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 may be specified by separating the end
characters of the range with a -
. All classes %x
described
above may 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.
[%a-z]
or [a-%%]
have no meaning.
[^set]
represents the complement of set
, where set
is interpreted
as above.
%a
, %c
, etc.), the
corresponding uppercase letter represents the complement of the class. For
instance, %S
represents all non-space characters.
[a-z]
may not be equivalent to %l
.
*
, 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
occurrences 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.
^
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*(.)%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.
()
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.
%z
instead.
table
.
{table}
[, {sep}
[, {i}
[, {j}
]]]) table.concat()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}
, {f}
) table.foreach(){f}
over all elements of {table}
. For each element,
{f}
is called with the index and respective value as arguments. If {f}
returns a non-`nil` value, then the loop is broken, and this value is
returned as the final value of table.foreach
.
{table}
, {f}
) table.foreachi(){f}
over the numerical indices of {table}
. For each
index, {f}
is called with the index and respective value as arguments.
Indices are visited in sequential order, from 1 to n
, where n
is
the length of the table. If {f}
returns a non-`nil` value, then the
loop is broken and this value is returned as the result of
table.foreachi
.
{table}
, [{pos}
,] {value}
) table.insert(){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
lua-length), so that a call table.insert(t,x)
inserts x
at the end of table t
.
{table}
) table.maxn(){table}
[, {pos}
]) table.remove(){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 (see lua-length), so that a call
table.remove(t)
removes the last element of table t
.
{table}
[, {comp}
]) table.sort()in-place
, from table[1]
to
table[n]
, where n
is the length of the table (see lua-length).
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.
not
stable, that is, elements considered equal by the
given order may have their relative positions changed by the sort.
math
.
{x}
, {y}
) math.atan2()x/y
(in radians), but uses the signs of
both parameters to find the quadrant of the result. (It also handles
correctly the case of {y}
being zero.)
{x}
) math.frexp()m
and e
such that x = m * 2^e
, e
is an integer and the
absolute value of m
is in the range [0.5, 1)
(or zero when {x}
is
zero).
{x}
) math.modf(){x}
and the fractional part
of {x}
.
{x}
, {y}
) math.pow()x^y
. (You can also use the expression x^y
to compute this
value.)
{m}
[, {n}
]]) math.random()rand
provided by ANSI C. (No guarantees can be given for
its statistical properties.)
[0,1)
. When called with a number {m}
, math.random
returns a pseudo-random integer in the range [1, m]
. When called
with two numbers {m}
and {n}
, math.random
returns a pseudo-random
integer in the range [m, n]
.
{x}
) math.randomseed(){x}
as the "seed" for the pseudo-random generator: equal seeds
produce equal sequences of numbers.
{x}
) math.sqrt(){x}
. (You can also use the expression
x^0.5
to compute this value.)
io
. When using explicit file descriptors, the operation io.open
returns
a file descriptor and then all operations are supplied as methods of the file
descriptor.
io
also provides three predefined file descriptors with their usual
meanings from C: io.stdin
, io.stdout
, and io.stderr
.
nil
on failure (plus an
error message as a second result) and some value different from nil
on
success.
{file}
]) io.close()file:close
. Without a {file}
, closes the default
output file.
{file}
]) io.input(){filename}
]) io.lines()for line in io.lines(filename) do
body
end
nil
(to finish the loop) and
automatically closes the file.
io.lines()
(without a file name) is equivalent to
io.input():lines()
; that is, it iterates over the lines of the
default input file. In this case it does not close the file when the
loop ends.
{filename}
[, {mode}
]) io.open(){mode}
. It returns a new file handle, or, in case of errors, nil
plus an error message.
{mode}
string can be any of the following:
"r"
read mode (the default);
"w"
write mode;
"a"
append mode;
"r+"
update mode, all previous data is preserved;
"w+"
update mode, all previous data is erased;
"a+"
append update mode, previous data is preserved, writing is
only allowed at the end of file.
{mode}
string may also have a b
at the end, which is needed in
some systems to open the file in binary mode. This string is exactly
what is used in the standard C function fopen
.
{prog}
[, {mode}
]) io.popen(){prog}
in a separated process and returns a file handle
that you can use to read data from this program (if {mode}
is "r"
,
the default) or to write data to this program (if {mode}
is "w"
).
{obj}
) io.type(){obj}
is a valid file handle. Returns the string
"file"
if {obj}
is an open file handle, "closed file"
if {obj}
is
a closed file handle, or nil
if {obj}
is not a file handle.
file
. Note that files are automatically closed when their
handles are garbage collected, but that takes an unpredictable amount
of time to happen.
for line in file:lines() do
body
end
io.lines
, this
function does not close the file when the loop ends.)
{...}
) file:read()file
, according to the given formats, which specify
what to read. For each format, the function returns a string (or a
number) with the characters read, or nil
if it cannot read data with
the specified format. When called without formats, it uses a default
format that reads the entire next line (see below).
"*n"
reads a number; this is the only format that returns a
number instead of a string.
"*a"
reads the whole file, starting at the current position. On
end of file, it returns the empty string.
"*l"
reads the next line (skipping the end of line), returning
nil
on end of file. This is the default format.
number
reads a string with up to that number of characters,
returning nil
on end of file. If number is zero, it reads
nothing and returns an empty string, or nil
on end of file.
{whence}
] [, {offset}
]) file:seek(){offset}
plus a base specified by the
string {whence}
, as follows:
"set"
: base is position 0 (beginning of the file);
"cur"
: base is current position;
"end"
: base is end of file;
seek
returns the final file position,
measured in bytes from the beginning of the file. If this function
fails, it returns nil
, plus a string describing the error.
{whence}
is "cur"
, and for {offset}
is 0.
Therefore, the call file:seek()
returns the current file position,
without changing it; the call file:seek("set")
sets the position to
the beginning of the file (and returns 0); and the call
file:seek("end")
sets the position to the end of the file, and
returns its size.
{mode}
[, {size}
]) file:setvbuf()"no"
no buffering; the result of any output operation appears
immediately.
"full"
full buffering; output operation is performed only when
the buffer is full (or when you explicitly flush
the file
(see io.flush()).
"line"
line buffering; output is buffered until a newline is
output or there is any input from some special files (such as
a terminal device).
{size}
specifies the size of the buffer, in
bytes. The default is an appropriate size.
{...}
) file:write()file
. The arguments
must be strings or numbers. To write other values, use tostring
tostring() or string.format
string.format() before
write
.
os
.
{format}
[, {time}
]]) os.date(){format}
.
{time}
argument is present, this is the time to be formatted
(see the os.time
function os.time() for a description of this
value). Otherwise, date
formats the current time.
{format}
starts with !
, then the date is formatted in
Coordinated Universal Time. After this optional character, if {format}
is the string "*t"
, then date
returns a table with the following
fields: year
(four digits), month
(1-12), day
(1-31), hour
(0-23), min
(0-59), sec
(0-61), wday
(weekday, Sunday is 1),
yday
(day of the year), and isdst
(daylight saving flag, a
boolean).
{format}
is not "*t"
, then date
returns the date as a string,
formatted according to the same rules as the C function strftime
.
date
returns a reasonable date and
time representation that depends on the host system and on the current
locale (that is, os.date()
is equivalent to os.date("%c")
).
{t2}
, {t1}
) os.difftime(){t1}
to time {t2}
. In POSIX,
Windows, and some other systems, this value is exactly t2 - t1
.
{command}
]) os.execute()system
. It passes
{command}
to be executed by an operating system shell. It returns a
status code, which is system-dependent. If {command}
is absent, then
it returns nonzero if a shell is available and zero otherwise.
{code}
]) os.exit()exit
, with an optional {code}
, to terminate the
host program. The default value for {code}
is the success code.
{varname}
) os.getenv(){varname}
, or
nil
if the variable is not defined.
{filename}
) os.remove()nil
, plus a string
describing the error.
{oldname}
, {newname}
) os.rename(){oldname}
to {newname}
. If this function fails, it
returns nil
, plus a string describing the error.
{locale}
[, {category}
]) os.setlocale(){locale}
is a string
specifying a locale; {category}
is an optional string describing which
category to change: "all"
, "collate"
, "ctype"
, "monetary"
,
"numeric"
, or "time"
; the default category is "all"
. The
function returns the name of the new locale, or nil
if the request
cannot be honored.
{table}
]) os.time()year
, month
, and day
, and may have fields
hour
, min
, sec
, and isdst
(for a description of these fields,
see the os.date
function os.date()).
time
can be used only as an argument to date
and difftime
.
debug
table. All
functions that operate over a thread have an optional first argument which is
the thread to operate over. The default is always the current thread.
cont
finishes this function, so that the caller continues its
execution.
debug.debug
are not lexically nested within
any function, and so have no direct access to local variables.
{thread}
]) debug.gethook()debug.sethook
function).
{thread}
,] {function}
[, {what}
]) debug.getinfo(){function}
, which means the function running at level {function}
of
the call stack of the given thread: level 0 is the current function
(getinfo
itself); level 1 is the function that called getinfo
; and
so on. If {function}
is a number larger than the number of active
functions, then getinfo
returns nil
.
lua_getinfo
(see lua_getinfo()), with the string {what}
describing which fields to fill in. The default for {what}
is to get
all information available, except the table of valid lines. If
present, the option f
adds a field named func
with the function
itself. If present, the option L
adds a field named activelines
with the table of valid lines.
debug.getinfo(1,"n").name
returns the
name of the current function, if a reasonable name can be found, and
debug.getinfo(print)
returns a table with all available information
about the print
function.
{thread}
,] {level}
, {local}
) debug.getlocal(){local}
of the function at level {level}
of the stack. (The
first parameter or local variable has index 1, and so on, until the
last active local variable.) The function returns nil
if there is no
local variable with the given index, and raises an error when called
with a {level}
out of range. (You can call debug.getinfo
debug.getinfo() to check whether the level is valid.)
(
(open parentheses) represent
internal variables (loop control variables, temporaries, and C
function locals).
{object}
) debug.getmetatable(){object}
or nil
if it does not
have a metatable.
{func}
, {up}
) debug.getupvalue(){up}
of the function {func}
. The function returns nil
if there is no
upvalue with the given index.
{object}
, {table}
) debug.setfenv(){object}
to the given {table}
.
Returns {object}
.
{thread}
,] {hook}
, {mask}
[, {count}
]) debug.sethook(){mask}
and the number
{count}
describe when the hook will be called. The string mask may
have the following characters, with the given meaning:
"c"
: The hook is called every time Lua calls a function;
"r"
: The hook is called every time Lua returns from a function;
"l"
: The hook is called every time Lua enters a new line of
code.
{count}
different from zero, the hook is called after every
{count}
instructions.
debug.sethook
turns off the hook.
"call"
, "return"
(or"tail
return"`), "line"
, and "count"
. For line events, the hook also
gets the new line number as its second parameter. Inside a hook, you
can call getinfo
with level 2 to get more information about the
running function (level 0 is the getinfo
function, and level 1 is
the hook function), unless the event is "tail return"
. In this case,
Lua is only simulating the return, and a call to getinfo
will return
invalid data.
{thread}
,] {level}
, {local}
, {value}
) debug.setlocal(){value}
to the local variable with
index {local}
of the function at level {level}
of the stack. The
function returns nil
if there is no local variable with the given
index, and raises an error when called with a {level}
out of range.
(You can call getinfo
to check whether the level is valid.)
Otherwise, it returns the name of the local variable.
{object}
, {table}
) debug.setmetatable(){object}
to the given {table}
(which
can be nil
).
{func}
, {up}
, {value}
) debug.setupvalue(){value}
to the upvalue with index {up}
of the function {func}
. The function returns nil
if there is no
upvalue with the given index. Otherwise, it returns the name of the
upvalue.
{thread}
,] [{message}
[,{level}
]]) debug.traceback(){message}
string is appended at the beginning of the traceback. An
optional {level}
number tells at which level to start the traceback
(default is 1, the function calling traceback
).