3.3.3 – Assignment
Lua allows multiple assignments. Therefore, the syntax for assignment defines a list of variables on the left side and a list of expressions on the right side. The elements in both lists are separated by commas:
stat ::= varlist ‘=’ explist varlist ::= var {‘,’ var} explist ::= exp {‘,’ exp}
Expressions are discussed in §3.4.
Before the assignment, the list of values is adjusted to the length of the list of variables. If there are more values than needed, the excess values are thrown away. If there are fewer values than needed, the list is extended with as many nil's as needed. If the list of expressions ends with a function call, then all values returned by that call enter the list of values, before the adjustment (except when the call is enclosed in parentheses; see §3.4).
The assignment statement first evaluates all its expressions and only then the assignments are performed. Thus the code
i = 3 i, a[i] = i+1, 20
sets a[3]
to 20, without affecting a[4]
because the i
in a[i]
is evaluated (to 3) before it is assigned 4. Similarly, the line
x, y = y, x
exchanges the values of x
and y
, and
x, y, z = y, z, x
cyclically permutes the values of x
, y
, and z
.
The meaning of assignments to global variables and table fields can be changed via metatables. An assignment to an indexed variable t[i] = val
is equivalent to settable_event(t,i,val)
. (See §2.4 for a complete description of the settable_event
function. This function is not defined or callable in Lua. We use it here only for explanatory purposes.)
An assignment to a global name x = val
is equivalent to the assignment _ENV.x = val
(see §2.2).
Please login to continue.