The Lua Language (V5.1) Cheat Sheet Page 2

ADVERTISEMENT

Garbage collection
Pseudo-random numbers
collectgarbage (opt [, arg])
generic interface to the garbage collector; opt defines function performed.
math.random ([n [, m])
returns a pseudo-random number in range [0, 1] if no arguments given; in range [1, n] if n is
given, in range [n, m] if both n and m are passed.
M o d u l e s a n d t h e p a c k a g e l i b r a r y [ p a c k a g e ]
math.randomseed (n)
sets a seed n for random sequence (same seed = same sequence)
module (name, ...)
creates module name. If there is a table in package.loaded[name], this table is the module.
T h e s t r i n g l i b r a r y [ s t r i n g ]
Otherwise, if there is a global table name, this table is the module. Otherwise creates a new
table and sets it as the value of the global name and the value of package.loaded[name].
Note: string indexes extend from 1 to #string, or from end of string if negative (index -1 refers to the last character).
Optional arguments are functions to be applied over the module.
Note: the string library sets a metatable for strings where the __index field points to the string table. String functions can be used
package.loadlib (lib, func)
loads dynamic library lib (e.g. .so or .dll) and returns function func (or nil and error message)
in object-oriented style, e.g. string.len(s) can be written s:len(); literals have to be enclosed in parentheses, e.g. ("xyz"):len().
package.path, package.cpath contains the paths used by require() to search for a Lua or C loader, respectively
Basic operations
package.loaded
a table used by require to control which modules are already loaded (see module)
string.len (s)
returns the length of string s, including embedded zeros (see also # operator)
package.preload
a table to store loaders for specific modules (see require)
string.sub (s, i [, j])
returns the substring of s from position i to j [default: -1] inclusive
package.seeall (module)
sets a metatable for module with its __index field referring to the global environment
string.rep (s, n)
returns a string made of n concatenated copies of string s
T h e c o r o u t i n e l i b r a r y [ c o r o u t i n e ]
string.upper (s)
returns a copy of s converted to uppercase according to locale
string.lower (s)
returns a copy of s converted to lowercase according to locale
coroutine.create (f)
creates a new coroutine with Lua function f() as body and returns it
coroutine.resume (co, args)
starts or continues running coroutine co, passing args to it; returns true (and possibly values)
Character codes
if co calls coroutine.yield() or terminates or false and an error message.
string.byte (s [, i [, j]])
returns the platform-dependent numerical code (e.g. ASCII) of characters s[i], s[i+1], ···, s[j]. The
coroutine.yield (args)
suspends execution of the calling coroutine (not from within C functions, metamethods or
default value for i is 1; the default value for j is i.
iterators); any args become extra return values of coroutine.resume().
string.char (args)
returns a string made of the characters whose platform-dependent numerical codes are passed as args
coroutine.status (co)
returns the status of coroutine co: either "running", "suspended" or "dead"
Function storage
coroutine.running ()
returns the running coroutine or nil when called by the main thread
string.dump (f)
returns a binary representation of function f(), for later use with loadstring() (f() must be a Lua
coroutine.wrap (f)
creates a new coroutine with Lua function f as body and returns a function; this function will
function with no upvalues)
act as coroutine.resume() without the first argument and the first return value, propagating
any errors.
Formatting
string.format (s [, args])
returns a copy of s where formatting directives beginning with '%' are replaced by the value of
T h e t a b l e l i b r a r y [ t a b l e ]
arguments args, in the given order (see Formatting directives below)
table.insert (t, [i,] v)
inserts v at numerical index i [default: after the end] in table t
table.remove (t [, i])
removes element at numerical index i [default: last element] from table t; returns the removed
Formatting directives for string.format
element or nil on empty table.
% [flags] [field_width] [.precision] type
table.maxn (t)
returns the largest positive numerical index of table t or zero if t has no positive indices
Formatting field types
table.sort (t [, cf])
sorts (in place) elements from t[1] to #t, using compare function cf(e1, e2) [default: '<']
%d
decimal integer
table.concat (t [, s [, i [, j]]])
returns a single string made by concatenating table elements t[i] to t[j] [default: i =1, j = #t]
octal integer
%o
separated by string s; returns empty string if no elements exist or i > j.
%x
hexadecimal integer, uppercase if %X
T h e m a t h e m a t i c a l l i b r a r y [ m a t h ]
%f
floating-point in the form [-]nnnn.nnnn
%e
floating-point in exp. Form [-]n.nnnn e [+|-]nnn, uppercase if %E
Basic operations
%g
floating-point as %e if exp. < -4 or >= precision, else as %f; uppercase if %G.
math.abs (x)
returns the absolute value of x
%c
character having the (system-dependent) code passed as integer
math.mod (x, y)
returns the remainder of x / y as a rounded-down integer, for y ~= 0
%s
string with no embedded zeros
math.floor (x)
returns x rounded down to the nearest integer
string between double quotes, with all special characters escaped
%q
math.ceil (x)
returns x rounded up to the nearest integer
%%
'%' character
math.min (args)
returns the minimum value from the args received
Formatting flags
math.max (args)
returns the maximum value from the args received
left-justifies within field_width [default: right-justify]
-
Exponential and logarithmic
+
prepends sign (only applies to numbers)
math.sqrt (x)
returns the square root of x, for x >= 0
(space)
prepends sign if negative, else blank space
math.pow (x, y)
returns x raised to the power of y, i.e. x^y; if x < 0, y must be integer.
#
adds "0x" before %x, force decimal point for %e, %f, leaves trailing zeros for %g
__pow (x, y)
global function added by the math library to make operator '^' work
Formatting field width and precision
math.exp (x)
returns e (base of natural logs) raised to the power of x, i.e. e^x
n
puts at least n (<100) characters, pad with blanks
math.log (x)
returns the natural logarithm of x, for x >= 0
0n
puts at least n (<100) characters, left-pad with zeros
math.log10 (x)
returns the base-10 logarithm of x, for x >= 0
.n
puts at least n (<100) digits for integers; rounds to n decimals for floating-point; puts no more than n
Trigonometrical
(<100) characters for strings.
math.deg (a)
converts angle a from radians to degrees
Formatting examples
math.rad (a)
converts angle a from degrees to radians
string.format("results: %d, %d", 13, 27)
results: 13, 27
constant containing the value of pi
math.pi
string.format("<%5d>", 13)
< 13>
math.sin (a)
returns the sine of angle a (measured in radians)
string.format("<%-5d>", 13)
<13 >
math.cos (a)
returns the cosine of angle a (measured in radians)
string.format("<%05d>", 13)
<00013>
math.tan (a)
returns the tangent of angle a (measured in radians)
string.format("<%06.3d>", 13)
< 013>
math.asin (x)
returns the arc sine of x in radians, for x in [-1, 1]
<3.141593>
string.format("<%f>", math.pi)
math.acos (x)
returns the arc cosine of x in radians, for x in [-1, 1]
string.format("<%e>", math.pi)
<3.141593e+00>
math.atan (x)
returns the arc tangent of x in radians
string.format("<%.4f>", math.pi)
<3.1416>
math.atan2 (y, x)
similar to math.atan(y / x) but with quadrant and allowing x = 0
string.format("<%9.4f>", math.pi)
< 3.1416>
Splitting on powers of 2
string.format("<%c>", 64)
<@>
math.frexp (x)
splits x into normalized fraction and exponent of 2 and returns both
string.format("<%.4s>", "goodbye")
<good>
math.ldexp (x, y)
returns x * (2 ^ y) with x = normalized fraction, y = exponent of 2
string.format("%q", [[she said "hi"]])
"she said \"hi\""
2

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 4