Basic Functions


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 message msg

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 if o 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". returns true, followed by an return values when no error occurs, otherwise returns false followed by an error message.

print (···)
Prints arguments ... to stdout, passing non-string values to tostring.

require (name)
Loads module name and returns it.

setmetatable (table)
Removes table's metatable (i.e., sets its metatable to nil) and returns table.
setmetatable (table, t)
Sets table's metatable to t and returns table.

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 base base 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 of list.
unpack (list, i, j)
Returns elements from indices i through j of list

xpcall (f, callback)
calls function f in "protected mode". returns true, followed by an return values when no error occurs, otherwise returns false followed by the return value(s) of callback(error), where error is the original error.