2.5 – Expressions

The basic expressions in Lua are the following:

  1. exp ::= prefixexp
  2. exp ::= nil | false | true
  3. exp ::= Number
  4. exp ::= Literal
  5. exp ::= function
  6. exp ::= tableconstructor
  7. prefixexp ::= var | functioncall | `(´ exp `)´

Numbers and literal strings are explained in 2.1; variables are explained in 2.3; function definitions are explained in 2.5.8; function calls are explained in 2.5.7; table constructors are explained in 2.5.6.

An 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.)

Expressions can also be built with arithmetic operators, relational operators, and logical operators, all of which are explained below.

2.5.1 – Arithmetic Operators

Lua supports the usual arithmetic operators: the binary + (addition), - (subtraction), * (multiplication), / (division), and ^ (exponentiation); and unary - (negation). If the operands are numbers, or strings that can be converted to numbers (see 2.2.1), then all operations except exponentiation have the usual meaning. Exponentiation calls a global function __pow; otherwise, an appropriate metamethod is called (see 2.8). The standard mathematical library defines function __pow, giving the expected meaning to exponentiation (see 5.5).

2.5.2 – 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. Objects (tables, userdata, threads, and functions) 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 function), this new object is different from any previously existing object.

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

The conversion rules of 2.2.1 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.8).

2.5.3 – Logical Operators

The logical operators in Lua are

  1. and or not

Like the control structures (see 2.4.4), all logical operators consider both false and nil as false and anything else as true.

The 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. For example,

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

2.5.4 – 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 2.2.1. Otherwise, the “concat” metamethod is called (see 2.8).

2.5.5 – 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. ^

You can use parentheses to change the precedences in an expression. The concatenation (`..´) and exponentiation (`^´) operators are right associative. All other binary operators are left associative.

2.5.6 – Table Constructors

Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. Constructors can be used to create empty tables, 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 temp = {}
  3. temp[f(1)] = g
  4. temp[1] = "x" -- 1st exp
  5. temp[2] = "y" -- 2nd exp
  6. temp.x = 1 -- temp["x"] = 1
  7. temp[3] = f(x) -- 3rd exp
  8. temp[30] = 23
  9. temp[4] = 45 -- 4th exp
  10. a = temp
  11. end

If the last field in the list has the form exp and the expression is a function call, then all values returned by the call enter the list consecutively (see 2.5.7). To avoid this, enclose the function call in parentheses (see 2.5).

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

2.5.7 – 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 that function is called with the given arguments. Otherwise, its “call” metamethod is called, having as first parameter the value of prefixexp, followed by the original call arguments (see 2.8).

The form

  1. functioncall ::= prefixexp `:´ Name args

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

Arguments have the following syntax:

  1. args ::= `(´ [explist1] `)´
  2. args ::= tableconstructor
  3. args ::= Literal

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

Because a function can return any number of results (see 2.4.4), the number of results must be adjusted before they are used. If the function is called as a statement (see 2.4.6), then its return list is adjusted to zero elements, thus discarding all returned values. If the function is called inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element, thus discarding all returned values except the first one. If the function is called as the last element of a list of expressions, then no adjustment is made (unless the call is enclosed in parentheses).

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 values returned by f()
  4. a,b,c = f(), x -- f() is adjusted to 1 result (and c gets nil)
  5. a,b,c = x, f() -- f() is adjusted to 2 results
  6. a,b,c = f() -- f() is adjusted to 3 results
  7. return f() -- returns all values returned by f()
  8. return x,y,f() -- returns x, y, and all values returned by f()
  9. {f()} -- creates a list with all values returned by f()
  10. {f(), nil} -- f() is adjusted to 1 result

If you enclose a function call in parentheses, then it is adjusted to return exactly one value:

  1. return x,y,(f()) -- returns x, y, and the first value from f()
  2. {(f())} -- creates a table with exactly one element

As an exception to the free-format syntax of Lua, you cannot put a line break before the `(´ in a function call. That restriction avoids some ambiguities in the language. If you write

  1. a = f
  2. (g).x(a)

Lua would read that as a = f(g).x(a). So, if you want two statements, you must add a semi-colon between them. If you actually want to call f, you must remove the line break before (g).

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 returns exactly the returns of the called function. So, all the following examples are not 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

2.5.8 – Function Definitions

The syntax for function definition is

  1. function ::= function funcbody
  2. funcbody ::= `(´ [parlist1] `)´ 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 () ... end

translates to

  1. f = function () ... end

The statement

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

translates to

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

The statement

  1. local function f () ... end

translates to

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

A function definition is an executable expression, whose value has type function. When Lua pre-compiles a chunk, all its function bodies are pre-compiled 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. Different instances of the same function may refer to different external local variables and may have different environment tables.

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

  1. parlist1 ::= namelist [`,´ `...´]
  2. parlist1 ::= `...´

When a function is called, the list of arguments is adjusted to the length of the list of parameters, unless the function is a variadic or 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 into an implicit parameter, called arg. The value of arg is a table, with a field `n´ that holds the number of extra arguments and with the extra arguments at positions 1, 2, …, n.

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:

  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, arg={n=0}
  10. g(3, 4) a=3, b=4, arg={n=0}
  11. g(3, 4, 5, 8) a=3, b=4, arg={5, 8; n=2}
  12. g(5, r()) a=5, b=1, arg={2, 3; n=2}

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

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 (...) ... end

is syntactic sugar for

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