Lua 5.1 A Short Reference
Lua 5.1 A Short Reference
Acknowledgments
Lua 5.1 Short Reference is a reformatted and updated version of Enrico Colombini s Lua 5.0 Short Reference (draft 2) in which he acknowledged others I am grateful to all people that contributed with notes and suggestions, including John Belmonte, Albert-Jan Brouwer, Tiago Dionizio, Marius Gheorghe, Asko Kauppi, Philippe Lhoste, Virgil Smith, Ando Sonenblick, Nick Trout and of course Roberto Ierusalimschy, whose Lua 5.0 Reference Manual and Programming in Lua have been my main sources of Lua lore. This Lua 5.1 update further acknowledges and thanks Enrico Colombini s for his Lua 5.0 Short Reference (draft 2) and Roberto Ierusalimschy s Lua 5.1 Reference Manual and Programming in Lua, 2nd Edition . This Short Reference update was done as a means of becoming familiar with Lua, so it has been edited and extended from the perspective of a new-comer to Lua. Graham Henstridge
Control structures
do block end while exp do block end repeat block until exp if exp then block {elseif exp then block} [else block] end for var = start, end [, step] do block end for k, v in iterator do block end break (exits loop, but must be last statement in block).
Reserved words
and break do else elseif end false function if in local nil not repeat return then true until while _A... A system variable, A = any uppercase letter. for or
Table constructors
t = {} A new empty table. t = {"yes", "no"} A new simple array, elements are t[1] = yes, t[2] = no. t = {[1] = "yes", [2] = "no"} Same as line above. t = {[-900] = 3, [+900] = 4} Sparse array, two elements. t = {x=5, y=10} Hash table or dictionary, fields t["x"], t["y"] or t.x, t.y. t = {x=5, y=10; "yes", "no"} Mixed fields: elements t.x, t.y, t[1], t[2]. t = {msg = "choice", {"yes", "no"}} Table containing a table as field.
Comments
---[[ ... --]] #! Comment to end of line. Multi-line comment. At start of first line for Linux executable.
Function definition
function name ( args ) body [return values] end Global function. local function name ( args ) body [return values] end Function local to chunk. f = function ( args ) body [return values] end Anonymous function. function ( ... ) body [return values] end (...) indicates variable args and {...} places them in a table where they processed in standard way. function t.name ( args ) body [return values] end Shortcut for t.name = function [...] function obj:name ( args ) body [return values] end Object function getting extra arg self. Functions can return multiple results.
Types
boolean number string table function thread userdata nil For booleans, nil and false count as false, all the rest is true including 0 and "" (null string). The type belongs to the value, NOT the variable to which it is assigned.
Function call
f ( args ) t.f (args) f string f {table} Simple call, returning zero or more values. Calling function stored in field f of table t. Calling with a single string argument Calling with a single table argument
Function examples
local function f ( mode, value ) body end a local function with two arguments. r = f {value = 3.14, mode = auto} By passing a table, args can be passed by name where function is defined: function f ( t ) body end, and arg accessed as t.value, t.mode.
Metatable operations
setmetatable ( t, mt ) Sets mt as metatable for t, unless t's metatable has a __metatable field. getmetatable ( t ) Returns __metatable field of t's metatable, or t's metatable, or nil. rawget ( t, i ) Gets t[i] of a table without invoking metamethods. rawset ( t, i, v ) Sets t[i] = v on a table without invoking metamethods. rawequal ( t1, t2 ) Returns boolean (t1 == t2) without invoking metamethods.
page 1 of 7
draft
xpcall ( f, h ) As pcall () but passes error handler h instead of extra args; returns as pcall () but with the result of h () as error message, if any (use debug.traceback () from the debug library for extended error info).
Iterators
ipairs ( t ) Returns an iterator getting index, value pairs of array t in numeric order. pairs ( t ) Returns an iterator getting key, value pairs of table t in no particular order. next ( t [, index] ) Returns next index-value pair (nil when finished) from index (default nil, i.e. beginning) of table t.
Garbage collection
collectgarbage ( opt [, v] ) where opt can be: stop Stops garbage collection. restart Restart garbage collection. collect Initiates a full garbage collection. count Returns total memory used. step Perform garbage collection step size v, returns true if it finished a cycle. setpause Set pause to v/100. setstepmul Sets multiplier to v/100. The garbage collector can be tuned using the pause and multiplier values: pause Determines how long waits, larger value is less aggressive. Default = 2. multiplier Controls speed of collection relative to memory allocation. Default = 2.
Coroutines
coroutine.create ( f ) Creates a new coroutine with function f, returns it. coroutine.resume ( co, args ) Starts or continues running coroutine co, passing args to it. Returns true (and possibly values) if co calls coroutine.yield ( ) or terminates, returns false and a message in case of error. coroutines.running ( ) Returns current running coroutine or nil if main thread. coroutine.yield ( args )
page 2 of 7
draft Suspends execution of the calling coroutine (not from within C functions, metamethods or iterators), any args become extra return values of coroutine.resume ( ). coroutine.status ( co ) Returns the status of coroutine co as a string: either "running", "suspended" or "dead". coroutine.wrap ( f ) Creates coroutine with function f as body and returns a function that acts as coroutine.resume ( ) without first arg and first return value, propagating errors. math.min( args ) math.max( args ) math.huge ( ) math.modf ( x ) Returns minimum value from args. Returns maximum value from args. Returns largest represented number Returns integer and fractional parts of x
Trigonometrical
math.deg ( a ) math.rad ( a ) math.pi math.sin ( a ) math.cos ( a ) math.tan ( a ) math.asin ( x ) math.acos ( x ) math.atan ( x )
Pseudo-random numbers
math.random ( [n [, m] ) Pseudo-random number in range [0, 1], [1, n] or [n, m]. math.randomseed ( n ) Sets a seed n for random sequence.
Path Formats
A path is a sequence of path templates separated by semicolons. For each template, require ( filename ) will substitute each ? by filename, in which each dot replaced by a "directory separator" ("/" in Linux); then it will try to load the resulting file name. Example: require ( dog.cat ) with path /usr/share/lua/?.lua;lua/?.lua will attempt to load cat.lua from /usr/share/lua/dog/ or lua/dog/
Character codes
string.byte ( s [, i] ) Ascii code of character at position i [default: 1] in string s, or nil if invalid i. string.char ( args ) Returns a string made of the characters whose ascii codes are passed as args.
Formatting
string.format ( s [, args] ) Returns a copy of s where formatting directives beginning with '%' are replaced by the value of arguments args. (see Formatting directives below)
draft string, alternatively with a nil or false return, original match is retained. Returns as second result, number of substitutions made (see Patterns below). () Stores current string position as capture % 1..%9, in order.
Function storage
string.dump ( f ) Returns binary representation of function f. Use with loadstring ( ). f must be Lua function with no upvalues. Note: String indexes go from 1 to string.len ( s ), from end of string if negative (index -1 refers to the last character).
Formatting flags
Left-justifies, default is right-justify. + Prepends sign (applies to numbers). (space) Prepends sign if negative, else space. # Adds "0x" before %x, force decimal point; for %e, %f, leaves trailing zeros for %g.
examples
string.find("Lua is great!", "is") >56 string.find("Lua is great!", "%s") >44 string.gsub("Lua is great!", "%s", "-") > Lua-is-great! 2 string.gsub("Lua is great!", "[%s%l]", "*") > L***********! 11 string.gsub("Lua is great!", "%a+", "*") > * * *! 3 string.gsub("Lua is great!", "(.)", "%1%1") > LLuuaa iiss ggrreeaatt!! 13 string.gsub("Lua is great!", "%but", "") > L! 1 string.gsub("Lua is great!", "^.-a", "LUA") > LUA is great! 1 string.gsub("Lua is great!", "^.-a", function (s) return string.upper(s) end) > LUA is great! 1
Formatting precision
Formatting examples
string.format ("dog: %d, %d",7,27) string.format ("<%5d>", 13) string.format ("<%-5d>", 13) string.format ("<%05d>", 13) string.format ("<%06.3d>", 13) string.format ("<%f>", math.pi) string.format ("<%e>", math.pi) string.format ("<%.4f>", math.pi) string.format ("<%9.4f>", math.pi) string.format ("<%c>", 64) string.format ("<%s.4>", "goodbye") string.format("%q",[[she said "hi"]])
Complete I/O
io.open ( fn [, m] ) Opens file with name fn in mode m: "r" = read [default], "w" = write, "a" = append, "r+" = update-preserve, "w+" = update-erase, "a+" = update-append (add trailing "b" for binary mode on some systems), returns a file object (an userdata with a C handle) usable with ':' syntax. Note in the following that file: is an io meta-method call. file:close ( ) Closes file. file:read ( formats ) Returns a value from file for each of the passed formats: "*n" = reads a number, "*a" = reads whole file as a string from current position ("" at end of file), "*l" = reads a line (nil at end of file) [default], n = reads a string of up to n characters (nil at end of file). page 4 of 7
Pattern captures
(sub_pattern) Stores substring matching sub_pattern as capture %1..%9, in order.
draft file:lines ( ) Returns an iterator function reading line-by-line from file; the iterator does not close the file when finished. file:write ( values ) Write each of values (strings or numbers) to file, with no added separators. Numbers are written as text, strings can contain binary data (may need binary mode read). file:seek ( [p] [, of] ) Sets current position in file relative to p ("set" = start of file [default], "cur" = current, "end" = end of file) adding offset of [default: zero]; returns new position in file. file:flush ( ) Writes to file any data still held in memory buffers. %b %B %c %d %H %I %M %m %p %S %w %x %X %y %Y Abbreviated month name. Full month name. Date/time (default) Day of month (01..31). Hour (00..23). Hour (01..12). Minute (00..59). Month (01..12). Either am or pm. Second (00..61). Weekday (0..6), 0 is Sunday. Date only. Time only. Year (nn). Year(nnnn).
Simple I/O
io.input ( [file] ) Sets file as default input file; file can be either an open file object or a file name; in the latter case the file is opened for reading in text mode; returns a file object, the current one if no file given; raises error on failure. io.output ( [file] ) Sets file as default output file (current output file is not closed); file can be either an open file object or a file name; in the latter case file is opened for writing in text mode. Returns a file object, the current one if no file given. Raises error on failure. io.close ( [file] ) Closes file object file. Default: closes default output file. io.read ( formats ) Reads from default input file, same as file:read ( ). io.lines ( [fn] ) Opens file name fn for reading. Returns an iterator function reading from it line-by-line. Iterator closes file when finished. If no fn, returns iterator reading lines from default input file. io.write ( values ) Writes to the default output file, same as file:write ( ). io.flush ( ) Writes to default output file any data in buffers.
System interaction
os.execute ( cmd ) Calls system shell to execute string cmd, returning status code. os.exit ( [code] ) Terminates script, returning code [default: success]. os.getenv ( var ) Returns a string with the value of the environment variable named var, or nil if no such variable exists. os.setlocale ( s [, c] ) Sets the locale described by string s for category c: "all" (default), "collate", "ctype", "monetary", "numeric" or "time". Returns name of new locale, or nil if not set. os.remove ( fn ) Deletes file fn, or returns nil and error description. os.rename ( of, nf ) Renames file of to nf, or returns nil and error message. os.tmpname ( ) Returns a string usable as name for a temporary file.
Basic functions
debug.debug ( ) Enters interactive debugging shell (type cont to exit); local variables cannot be accessed directly. debug.getfenv ( o ) Returns the environment of object o debug.getinfo ( [c,] f [, w] ) Returns table with information for function f in coroutine c or for function at level f [1 = caller], or nil if invalid level. Table keys are: source Name of file (prefixed by '@') or string where f defined. short_src Short version of source, up to 60 characters. linedefined Line of source where the function was defined. what "Lua" = Lua function, "C" = C function, "main" = part of main chunk. name Name of function, if available, or a reasonable guess if possible. namewhat Meaning of name: "global", "local", "method", "field" or "". nups Number of upvalues of the function. func The function itself. page 5 of 7
The OS Library
Many characteristics of this library are determined by operating system support.
Date/time
Time and date accessed via time-table tt = {year = 1970-2135 , month = 1-12, day = 1-31, hour = 0-23, min = 0-59, sec = 0-59, isdst = true-false,} os.time ( [tt] ) Returns date/time, in seconds since epoch, described by table tt [default: current]. Requires year, month, day; while hour, min, sec, isdst fields optional. os.difftime ( t2, t1 ) Returns difference between two os.time ( ) values. os.date ( [fmt [, t]] ) Returns a table or string describing date/time t (that should be a value returned by os.time), according to the format string fmt: ! A leading ! requests UTC time *t Returns a table similar to time-table while the following format a string representation: %a Abbreviated weekday name. %A Full weekday name.
draft Characters in string w select one or more groups of fields (default is all): n Returns fields name and namewhat. f Returns field func. S Returns fields source, short_src, what and linedefined. l Returns field currentline. u Returns field nup. debug.getlocal ( [c,] n, i ) Returns name and value of local variable at index i (from 1, in order of appearance) of the function at stack level n (1= caller) in coroutine c; returns nil if i is out of range, raises error if n is out of range. debug.gethook ( [c] ) Returns current hook function, mask and count set with debug.sethook ( ) for coroutine c. debug.getmetatable ( o ) Returns metatable of object o or nil if none. debug.getregistry ( ) Returns registry table that contains static library data. debug.getupvalue ( f, i ) Returns name and value of upvalue at index i (from 1, in order of appearance) of function f. If i is out of range, returns nil. debug.traceback ( [c,] [msg] ) Returns a string with traceback of call stack, prepended by msg. Coroutine c may be specified. debug.setfenv ( o, t ) Sets environment of object o to table t. Returns o. debug.sethook ( [[c,] h, m [, n]] ) For coroutine c, sets function h as hook, called for events given in mask string m: "c" = function call, "r" = function return, "l" = new code line, optionally call h ( ) every n instructions. Event type received by h ( ) as first argument: "call", "return", "tail return", "line" (line number as second argument) or "count". Use debug.getinfo (2) inside h ( ) for info (not for "tail_return"). debug.setlocal ( [c,] n, i, v ) Assigns value v to the local variable at index i (from 1, in order of appearance) of the function at stack level n (1= caller); returns nil if i is out of range, raises error if n is out of range. Coroutine c may be specified. debug.setmatatable ( o, t ) Sets metatable of object o to table t, which can be nil. debug.setupvalue ( f, i, v ) Assigns value v to upvalue at index i (from 1, in order of appearance) of function f. Returns nil if i is out of range.
The Compiler
Command line syntax
luac [options] [scripts]
Options
Compiles from standard input. Produces a listing of the compiled bytecode. Sends output to filename [default: luac.out]. -p Performs syntax and integrity checking only, does not output bytecode. -s Strips debug information; line numbers and local names are lost. -v Prints version information. -Stops parsing options. Compiled chunks portable on machines with same word size. -l -o filename
Independent Libraries
Lua core is designed to be a minimalist, portable and modern scripting language. As such it has only basic libraries. Independent libraries add functionality. Some useful libraries include:
bitlib library
The small elegantly written library by Reuben Thomas provides a useful set of bit-wise functions to Lua. All function arguments should be integers. Non integers can return unexpected results. bit.bnot ( a ) One's complement of a. bit.band ( w1, ... ) Bitwise and of the w's bit.bor ( w1, ... ) Bitwise or of the w's bit.bxor ( w1, ... ) Bitwise exclusive or of the w's bit.lshift ( a, b ) a shifted left b places bit.rshift ( a, b ) a shifted logically right b places bit.arshift ( a, b ) a shifted arithmetically right b places bit.mod ( a, b ) Integer remainder of a divided by b
Options
-e stats Loads and executes script from standard input (no args allowed). Executes the Lua statements contained in the literal string stats, can be used multiple times on same line. Loads and executes filename if not already loaded. Enters interactive mode after loading and execution of script. Prints version information. Stops parsing options. If it contains a string in the form @filename loads and executes filename, else executes the string itself. Sets the prompt for interactive mode.
-l filename -i -v -LUA_INIT
_PROMPT
page 6 of 7
draft lfs.dir ( path ) Returns an iterator function that returns a string for each entry directory, nil no more entries. Raises error if path not a directory. lfs.lock ( filehandle, mode[, start[, length]] ) Locks an open file or a part of it. Mode "r" for a read/ shared lock or "w" for a write/exclusive lock. Starting point start and length length both numbers. Returns true or nil and error string. lfs.mkdir ( dirname ) Creates a new directory dirname. Returns true or nil and error string. lfs.rmdir ( dirname ) Removes directory dirname. Returns true or nil and error string. lfs.touch ( filepath [, atime [, mtime]] ) Set access atime and modification mtime times of file filepath. Times in seconds as os.date(). Defaults to current time. Returns true or nil plus an error string. lfs.unlock ( filehandle[, start[, length]] ) Unlocks an open file or a part of it. Start and length both numbers. Returns true or nil plus an error string.
Examples
lfs.attributes( /var/spool/mail/root, size ) returns the size of root in bytes for f in lfs.dir ( /tmp ) do print ( f ) end prints all files and directories in /tmp directory
page 7 of 7