3.4 – Expressions

The basic expressions in Lua are the following:

  1. exp ::= prefixexp
  2. exp ::= nil | false | true
  3. exp ::= Number
  4. exp ::= String
  5. exp ::= functiondef
  6. exp ::= tableconstructor
  7. exp ::= ...
  8. exp ::= exp binop exp
  9. exp ::= unop exp
  10. prefixexp ::= var | functioncall | ( exp )

Numbers and literal strings are explained in §3.1; variables are explained in §3.2; function definitions are explained in §3.4.10; function calls are explained in §3.4.9; table constructors are explained in §3.4.8. Vararg expressions, denoted by three dots (‘...‘), can only be used when directly inside a vararg function; they are explained in §3.4.10.

Binary operators comprise arithmetic operators (see §3.4.1), relational operators (see §3.4.3), logical operators (see §3.4.4), and the concatenation operator (see §3.4.5). Unary operators comprise the unary minus (see §3.4.1), the unary not (see §3.4.4), and the unary length operator (see §3.4.6).

Both function calls and vararg expressions can result in multiple values. If a function call is used as a statement (see §3.3.6), 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 expression is enclosed in parentheses). In all other contexts, Lua adjusts the result list to one element, either discarding all values except the first one or adding a single nil if there are no values.

Here are some examples:

  1. f() -- adjusted to 0 results
  2. g(f(), x) -- f() is adjusted to 1 result
  3. g(x, f()) -- g gets x plus all results from f()
  4. a,b,c = f(), x -- f() is adjusted to 1 result (c gets nil)
  5. a,b = ... -- a gets the first vararg parameter, b gets
  6. -- the second (both a and b can get nil if there
  7. -- is no corresponding vararg parameter)
  8.  
  9. a,b,c = x, f() -- f() is adjusted to 2 results
  10. a,b,c = f() -- f() is adjusted to 3 results
  11. return f() -- returns all results from f()
  12. return ... -- returns all received vararg parameters
  13. return x,y,f() -- returns x, y, and all results from f()
  14. {f()} -- creates a list with all results from f()
  15. {...} -- creates a list with all vararg parameters
  16. {f(), nil} -- 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 nil if f does not return any values.)

3.4.1 – Arithmetic Operators

Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), % (modulo), and ^ (exponentiation); and unary - (mathematical negation). If the operands are numbers, or strings that can be converted to numbers (see §3.4.2), then all operations have the usual meaning. Exponentiation works for any exponent. For instance, x^(-0.5) computes the inverse of the square root of x. Modulo is defined as

  1. a % b == a - math.floor(a/b)*b

That is, it is the remainder of a division that rounds the quotient towards minus infinity.

3.4.2 – Coercion

Lua provides automatic conversion between string and number values at run time. Any arithmetic operation applied to a string tries to convert this string to a number, following the rules of the Lua lexer. (The string may have leading and trailing spaces and a sign.) Conversely, whenever a number is used where a string is expected, the number is converted to a string, in a reasonable format. For complete control over how numbers are converted to strings, use the format function from the string library (see string.format).

3.4.3 – Relational Operators

The relational operators in Lua are

  1. == ~= < > <= >=

These operators always result in false or true.

Equality (==) first compares the type of its operands. If the types are different, then the result is false. Otherwise, the values of the operands are compared. Numbers and strings are compared in the usual way. Tables, userdata, and threads are compared by reference: two objects are considered equal only if they are the same object. Every time you create a new object (a table, userdata, or thread), this new object is different from any previously existing object. Closures with the same reference are always equal. Closures with any detectable difference (different behavior, different definition) are always different.

You can change the way that Lua compares tables and userdata by using the “eq” metamethod (see §2.4).

The conversion rules of §3.4.2 do not apply to equality comparisons. Thus, "0"==0 evaluates to false, and t[0] and t["0"] denote different entries in a table.

The operator ~= is exactly the negation of equality (==).

The order operators work as follows. If both arguments are numbers, then they are compared as such. Otherwise, if both arguments are strings, then their values are compared according to the current locale. Otherwise, Lua tries to call the “lt” or the “le” metamethod (see §2.4). A comparison a > b is translated to b < a and a >= b is translated to b <= a.

3.4.4 – Logical Operators

The logical operators in Lua are and, or, and not. Like the control structures (see §3.3.4), all logical operators consider both false and nil as false and anything else as true.

The negation operator not always returns false or true. The conjunction operator and returns its first argument if this value is false or nil; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false; otherwise, or returns its second argument. Both and and or use short-cut evaluation; that is, the second operand is evaluated only if necessary. Here are some examples:

  1. 10 or 20 --> 10
  2. 10 or error() --> 10
  3. nil or "a" --> "a"
  4. nil and 10 --> nil
  5. false and error() --> false
  6. false and nil --> false
  7. false or nil --> nil
  8. 10 and 20 --> 20

(In this manual, --> indicates the result of the preceding expression.)

3.4.5 – Concatenation

The string concatenation operator in Lua is denoted by two dots (‘..‘). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §3.4.2. Otherwise, the __concat metamethod is called (see §2.4).

3.4.6 – The Length Operator

The length operator is denoted by the unary prefix operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).

A program can modify the behavior of the length operator for any value but strings through the __len metamethod (see §2.4).

Unless a __len metamethod is given, the length of a table t is only defined if the table is a sequence, that is, the set of its positive numeric keys is equal to {1..n} for some non-negative integer n. In that case, n is its length. Note that a table like

  1. {10, 20, nil, 40}

is not a sequence, because it has the key 4 but does not have the key 3. (So, there is no n such that the set {1..n} is equal to the set of positive numeric keys of that table.) Note, however, that non-numeric keys do not interfere with whether a table is a sequence.

3.4.7 – Precedence

Operator precedence in Lua follows the table below, from lower to higher priority:

  1. or
  2. and
  3. < > <= >= ~= ==
  4. ..
  5. + -
  6. * / %
  7. not # - (unary)
  8. ^

As usual, you can use parentheses to change the precedences of an expression. The concatenation (‘..‘) and exponentiation (‘^‘) operators are right associative. All other binary operators are left associative.

3.4.8 – Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is

  1. tableconstructor ::= { [fieldlist] }
  2. fieldlist ::= field {fieldsep field} [fieldsep]
  3. field ::= [ exp ] = exp | Name = exp | exp
  4. fieldsep ::= , | ;

Each field of the form [exp1] = exp2 adds to the new table an entry with key exp1 and value exp2. A field of the form name = exp is equivalent to ["name"] = exp. Finally, fields of the form exp are equivalent to [i] = exp, where i are consecutive numerical integers, starting with 1. Fields in the other formats do not affect this counting. For example,

  1. a = { [f(1)] = g; "x", "y"; x = 1, f(x), [30] = 23; 45 }

is equivalent to

  1. do
  2. local t = {}
  3. t[f(1)] = g
  4. t[1] = "x" -- 1st exp
  5. t[2] = "y" -- 2nd exp
  6. t.x = 1 -- t["x"] = 1
  7. t[3] = f(x) -- 3rd exp
  8. t[30] = 23
  9. t[4] = 45 -- 4th exp
  10. a = t
  11. end

If the last field in the list has the form exp and the expression is a function call or a vararg expression, then all values returned by this expression enter the list consecutively (see §3.4.9).

The field list can have an optional trailing separator, as a convenience for machine-generated code.

3.4.9 – Function Calls

A function call in Lua has the following syntax:

  1. functioncall ::= prefixexp args

In a function call, first prefixexp and args are evaluated. If the value of prefixexp has type function, then this function is called with the given arguments. Otherwise, the prefixexp “call” metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see §2.4).

The form

  1. functioncall ::= prefixexp : Name args

can be used to call “methods”. A call v:name(*args*) is syntactic sugar for v.name(v,*args*), except that v is evaluated only once.

Arguments have the following syntax:

  1. args ::= ( [explist] )
  2. args ::= tableconstructor
  3. args ::= String

All argument expressions are evaluated before the call. A call of the form f{*fields*} is syntactic sugar for f({*fields*}); that is, the argument list is a single new table. A call of the form f'*string*' (or f"*string*" or f[[*string*]]) is syntactic sugar for f('*string*'); that is, the argument list is a single literal string.

A call of the form return *functioncall* is called a tail call. Lua implements proper tail calls (or proper tail recursion): in a tail call, the called function reuses the stack entry of the calling function. Therefore, there is no limit on the number of nested tail calls that a program can execute. However, a tail call erases any debug information about the calling function. Note that a tail call only happens with a particular syntax, where the return has one single function call as argument; this syntax makes the calling function return exactly the returns of the called function. So, none of the following examples are tail calls:

  1. return (f(x)) -- results adjusted to 1
  2. return 2 * f(x)
  3. return x, f(x) -- additional results
  4. f(x); return -- results discarded
  5. return x or f(x) -- results adjusted to 1

3.4.10 – Function Definitions

The syntax for function definition is

  1. functiondef ::= function funcbody
  2. funcbody ::= ( [parlist] ) block end

The following syntactic sugar simplifies function definitions:

  1. stat ::= function funcname funcbody
  2. stat ::= local function Name funcbody
  3. funcname ::= Name {‘. Name} [‘: Name]

The statement

  1. function f () body end

translates to

  1. f = function () body end

The statement

  1. function t.a.b.c.f () body end

translates to

  1. t.a.b.c.f = function () body end

The statement

  1. local function f () body end

translates to

  1. local f; f = function () body end

not to

  1. local f = function () body end

(This only makes a difference when the body of the function contains references to f.)

A function definition is an executable expression, whose value has type function. When Lua precompiles a chunk, all its function bodies are precompiled too. Then, whenever Lua executes the function definition, the function is instantiated (or closed). This function instance (or closure) is the final value of the expression.

Parameters act as local variables that are initialized with the argument values:

  1. parlist ::= namelist [‘, ...’] | ...

When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a vararg function, which is indicated by three dots (‘...‘) at the end of its parameter list. A vararg function does not adjust its argument list; instead, it collects all extra arguments and supplies them to the function through a vararg expression, which is also written as three dots. The value of this expression is a list of all actual extra arguments, similar to a function with multiple results. If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses).

As an example, consider the following definitions:

  1. function f(a, b) end
  2. function g(a, b, ...) end
  3. function r() return 1,2,3 end

Then, we have the following mapping from arguments to parameters and to the vararg expression:

  1. CALL PARAMETERS
  2.  
  3. f(3) a=3, b=nil
  4. f(3, 4) a=3, b=4
  5. f(3, 4, 5) a=3, b=4
  6. f(r(), 10) a=1, b=10
  7. f(r()) a=1, b=2
  8.  
  9. g(3) a=3, b=nil, ... --> (nothing)
  10. g(3, 4) a=3, b=4, ... --> (nothing)
  11. g(3, 4, 5, 8) a=3, b=4, ... --> 5 8
  12. g(5, r()) a=5, b=1, ... --> 2 3

Results are returned using the return statement (see §3.3.4). If control reaches the end of a function without encountering a return statement, then the function returns with no results.

There is a system-dependent limit on the number of values that a function may return. This limit is guaranteed to be larger than 1000.

The colon syntax is used for defining methods, that is, functions that have an implicit extra parameter self. Thus, the statement

  1. function t.a.b.c:f (params) body end

is syntactic sugar for

  1. t.a.b.c.f = function (self, params) body end