Expressions
Learn about the basic expressions in Lua.
exp ::= prefixexp
exp ::= nil | null | false | true
exp ::= Number
exp ::= String
exp ::= function
exp ::= tableconstructor
exp ::= `...´
exp ::= exp binop exp
exp ::= unop exp
prefixexp ::= var | functioncall | `(´ exp `)´
Vararg expressions, denoted by three dots
(...
), can only be used when directly inside a vararg function.
Binary operators comprise arithmetic operators, relational operators, logical operators, and the concatenation operator. Unary operators comprise the unary minus, the unary not , and the unary length operator.
Both function calls and vararg expressions can result in multiple values. If an expression is used as a statement, which is only possible for function calls, then its return list is adjusted to zero elements, thus discarding all returned values. If an expression is used as the last (or the only) element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, discarding all values except the first one.
f() -- adjusted to 0 results
g(f(), x) -- f() is adjusted to 1 result
g(x, f()) -- g gets x plus all results from f()
a,b,c = f(), x -- f() is adjusted to 1 result (c gets null)
a,b = ... -- a gets the first vararg parameter, b gets
-- the second (both a and b can get null if there
a,b,c = x, f() -- is no corresponding vararg parameter
-- f() is adjusted to 2 results
a,b,c = f() -- f() is adjusted to 3 results
return f() -- returns all results from f()
return ... -- returns all received vararg parameters
return x,y,f() -- returns x, y, and all results from f()
{f()} -- creates a list with all results from f()
{...} -- creates a list with all vararg parameters
{f(), null} -- f() is adjusted to 1 result
Any expression enclosed in parentheses always results in only one value. Thus,
(f(x,y,z))
is always a single value, even if f
returns several
values. (The value of (f(x,y,z))
is the first value returned by f
or null if f
does not return any values.)