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
condis not truthy with message "assertion failed!" - assert(cond, msg)
- Raise an error if
condis 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 ifodoes 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
fwith optional arguments...in "protected mode". returnstrue, followed by an return values when no error occurs, otherwise returnsfalsefollowed by an error message. - print (···)
- Prints arguments
...to stdout, passing non-string values totostring. - require (name)
- Loads module
nameand returns it. - setmetatable (table)
- Removes
table's metatable (i.e., sets its metatable to nil) and returnstable. - setmetatable (table, t)
- Sets
table's metatable totand returnstable. - tonumber (arg)
- Converts
argto a number and returns it.argis expected to be a number or a string that represents a number. Otherwise, returns nil. - tonumber (arg, base)
- Converts
argto a number with basebaseand returns it.argis expected to be a number or a string that represents a number. Otherwise, returns nil. - tostring (arg)
- Converts
argto 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
ithrough the end oflist. - unpack (list, i, j)
- Returns elements from indices
ithroughjoflist - xpcall (f, callback)
- calls function
fin "protected mode". returnstrue, followed by an return values when no error occurs, otherwise returnsfalsefollowed by the return value(s) ofcallback(error), whereerroris the original error.