Lua includes a variety of basic functions that are useful when working with Lua.
These functions are always available, and can be accessed by name as shown in the following example:
print(type(123)) -- number
The most-commonly used functions are:
- assert(cond)
- Raise an error if
cond
is not truthy with message "assertion failed!" - assert(cond, msg)
- Raise an error if
cond
is not truthy with messagemsg
- dofile()
- Reads input from stdin and executes it, returning all values.
- dofile(path)
- Executes the lua file located at
path
, returning all values.. - getmetatable (o)
- Return the metatable from object
o
, of nil ifo
does not have a metatable. - ipairs (list)
- Returns (index, value) pairs from
list
. See iterating lists for more information. - pairs (map)
- Returns (key, value) pairs from
map
. See iterating maps for more information. - pcall (f, ···)
- calls function
f
with optional arguments...
in "protected mode". returnstrue
, followed by an return values when no error occurs, otherwise returnsfalse
followed by an error message. - print (···)
- Prints arguments
...
to stdout, passing non-string values totostring
. - require (name)
- Loads module
name
and returns it. - setmetatable (table)
- Removes
table
's metatable (i.e., sets its metatable to nil) and returnstable
. - setmetatable (table, t)
- Sets
table
's metatable tot
and returnstable
. - tonumber (arg)
- Converts
arg
to a number and returns it.arg
is expected to be a number or a string that represents a number. Otherwise, returns nil. - tonumber (arg, base)
- Converts
arg
to a number with basebase
and returns it.arg
is expected to be a number or a string that represents a number. Otherwise, returns nil. - tostring (arg)
- Converts
arg
to a string and returns it. - type (arg)
- Returns a string specifying the type of
arg
. - unpack (list)
- Returns the elements from
list
. - unpack (list, i)
- Returns elements from index
i
through the end oflist
. - unpack (list, i, j)
- Returns elements from indices
i
throughj
oflist
- xpcall (f, callback)
- calls function
f
in "protected mode". returnstrue
, followed by an return values when no error occurs, otherwise returnsfalse
followed by the return value(s) ofcallback(error)
, whereerror
is the original error.