The Lua Language (V5.1) Cheat Sheet

ADVERTISEMENT

T h e L u a l a n g u a g e ( v 5 . 1 )
f [[see you soon]]
shortcut for f([[see you soon]])
f {x = 3, y = 4}
shortcut for f({x = 3, y = 4})
Reserved identifiers and comments
t.f (x)
calling a function assigned to field f of table t
and
break
do
else
elseif
end
false
for
function
if
in
x:move (2, -3)
object call: shortcut for x.move(x, 2, -3)
local
nil
not
or
repeat
return
then
true
until
while
Metatable operations (base library required)
-- ...
comment to end of line
--[=[ ]=]
multi line comment (zero or multiple '=' are valid)
setmetatable (t, mt)
sets mt as metatable for t, unless t's metatable has a __metatable field, and returns t
_X is "reserved" (by convention) for constants (with X
#!
usual Unix shebang; Lua ignores whole first line if this
getmetatable (t)
returns __metatable field of t's metatable or t's metatable or nil
being any sequence of uppercase letters)
starts the line.
rawget (t, i)
gets t[i] of a table without invoking metamethods
Types (the string values are the possible results of base library function type())
rawset (t, i, v)
sets t[i] = v on a table without invoking metamethods
"nil"
"boolean"
"number"
"string"
"table"
"function"
"thread"
"userdata"
rawequal (t1, t2)
returns boolean (t1 == t2) without invoking metamethods
Note: for type boolean, nil and false count as false; everything else is true (including 0 and "").
Metatable fields (for tables and userdata)
Strings and escape sequences
__add, __sub sets handler h(a, b) for '+' and for binary '-'
__mul, __div
sets handler h(a, b) for '*' and for '/'
'...' and "..."
string delimiters; interpret escapes.
[=[...]=]
multi line string; escape sequences are ignored.
set handler h(a, b) for '%'
sets handler h(a, b) for '^'
__mod
__pow
\a bell
\b backspace
\f form feed
\n newline
\r return
\t horiz. tab
\v vert. tab
__unm
sets handler h(a) for unary '-'
__len
sets handler h(a) for the # operator (userdata)
\\ backslash
\" d. quote
\' quote
\[ sq. bracket
\] sq. bracket
\ddd decimal (up to 3 digits)
__concat
sets handler h(a, b) for '..'
__eq
sets handler h(a, b) for '==', '~='
__lt
sets handler h(a, b) for '<', '>' and possibly '<=',
__le
sets handler h(a, b) for '<=', '>='
Operators, decreasing precedence
'>=' (if no __le)
^ (right associative, math library required)
sets handler h(t, k) for access to non-existing
sets handler h(t, k, v) for assignment to non-
__index
__newindex
not
# (length of strings and tables)
- (unary)
field
existing field
*
/
%
__call
sets handler h(f, ...) for function call (using the
__tostring
sets handler h(a) to convert to string, e.g. for
+
-
object as a function)
print()
.. (string concatenation, right associative)
__gc
sets finalizer h(ud) for userdata (has to be set
__mode
table mode: 'k' = weak keys; 'v' = weak
<
>
<=
>=
~=
==
from C)
values; 'kv' = both.
and (stops on false or nil, returns last evaluated value)
__metatable
sets value to be returned by getmetatable()
or (stops on true (not false or nil), returns last evaluated value)
T h e b a s e l i b r a r y [ n o p r e f i x ]
Assignment and coercion
a = 5 b= "hi"
simple assignment; variables are not typed and can hold different types. Local variables are
Environment and global variables
lexically scoped; their scope begins after the full declaration (so that local a = 5).
local a = a
getfenv ([f])
if f is a function, returns its environment; if f is a number, returns the environment of function
a, b, c = 1, 2, 3
multiple assignments are supported
at level f (1 = current [default], 0 = global); if the environment has a field __fenv, returns that
a, b = b, a
swap values: right hand side is evaluated before assignment takes place
instead.
a, b = 4, 5, "6"
excess values on right hand side ("6") are evaluated but discarded
setfenv (f, t)
sets environment for function f (or function at level f, 0 = current thread); if the original
a, b = "there"
for missing values on right hand side nil is assumed
environment has a field __fenv, raises an error. Returns function f if f ~= 0.
a = nil
destroys a; its contents are eligible for garbage collection if unreferenced.
_G
global variable whose value is the global environment (that is, _G._G == _G)
a = z
if z is not defined it is nil, so nil is assigned to a (destroying it)
global variable containing the interpreter's version (e.g. "Lua 5.1")
_VERSION
a = "3" + "2"
numbers expected, strings are converted to numbers (a = 5)
Loading and executing
a = 3 .. 2
strings expected, numbers are converted to strings (a = "32")
require (pkgname)
loads a package, raises error if it can't be loaded
Control structures
dofile ([filename])
loads and executes the contents of filename [default: standard input]; returns its returned
do block end
block; introduces local scope.
values.
if exp then block {elseif exp then block} [else block] end
conditional execution
load (func [, chunkname])
loads a chunk (with chunk name set to name) using function func to get its pieces; returns
while exp do block end
loop as long as exp is true
compiled chunk as function (or nil and error message).
repeat block until exp
exits when exp becomes true; exp is in loop scope.
loadfile (filename)
loads file filename; return values like load().
for var = start, end [, step] do block end
numerical for loop; var is local to loop.
loadstring (s [, name])
loads string s (with chunk name set to name); return values like load().
for vars in iterator do block end
iterator based for loop; vars are local to loop.
pcall (f [, args])
calls f() in protected mode; returns true and function results or false and error message.
exits loop; must be last statement in block.
break
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.
Table constructors
creates an empty table and assigns it to t
t = {}
Simple output and error feedback
t = {"yes", "no", "?"}
simple array; elements are t[1], t[2], t[3].
print (args)
prints each of the passed args to stdout using tostring() (see below)
t = { [1] = "yes", [2] = "no", [3] = "?" }
same as above, but with explicit fields
error (msg [, n])
terminates the program or the last protected call (e.g. pcall()) with error message msg quoting
t = {[-900] = 3, [900] = 4}
sparse array with just two elements (no space wasted)
level n [default: 1, current function]
t = {x=5, y=10}
hash table, fields are t["x"], t["y"] (or t.x, t.y)
assert (v [, msg])
calls error(msg) if v is nil or false [default msg: "assertion failed!"]
t = {x=5, y=10; "yes", "no"}
mixed, fields/elements are t.x, t.y, t[1], t[2]
Information and conversion
t = {msg = "choice", {"yes", "no", "?"}}
tables can contain others tables as fields
select (index, ...)
returns the arguments after argument number index or (if index is "#") the total number of
Function definition
arguments it received after index
function name ( args ) body [return values] end
defines function and assigns to global variable name
type (x)
returns the type of x as a string (e.g. "nil", "string"); see Types above.
local function name ( args ) body [return values] end
defines function as local to chunk
tostring (x)
converts x to a string, using t's metatable's __tostring if available
f = function ( args ) body [return values] end
anonymous function assigned to variable f
tonumber (x [, b])
converts string x representing a number in base b [2..36, default: 10] to a number, or nil if
function ( [args, ] ... ) body [return values] end
variable argument list, in body accessed as ...
invalid; for base 10 accepts full format (e.g. "1.5e6").
function t.name ( args ) body [return values] end
shortcut for t.name = function ...
unpack (t)
returns t[1]..t[n] (n = #t) as separate values
function obj:name ( args ) body [return values] end
object function, gets obj as additional first argument self
Iterators
Function call
ipairs (t)
returns an iterator getting index, value pairs of array t in numerical order
f (x)
simple call, possibly returning one or more values
pairs (t)
returns an iterator getting key, value pairs of table t in an unspecified order
f "hello"
shortcut for f("hello")
next (t [, inx])
if inx is nil [default] returns first index, value pair of table t; if inx is the previous index
shortcut for f('goodbye')
f 'goodbye'
returns next index, value pair or nil when finished.
1

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 4