Assignment

<< Click to Display Table of Contents >>

Navigation:  Multi-Protocol MasterOPC Server > Lua 5.1 Reference Manual > The Language and syntax > Statements >

Assignment

Assignment

In Lua, the assignment operator is the symbol ’=’. In addition, Lua supports parallel assignment (that is, several variables can be assigned in one expression). In general, the assignment operator looks like a list of variables, the symbol ’=’ and a list of expressions. Elements of lists are separated by a comma:

a=b --assignment of the value "b" to the cariable "a"

a,b=c,d --assignment of the values "c" and "d" to the variables "a" and "b"

Expressions are discussed in Expressions .

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

The assignment statement first evaluates all its expressions and only then are the assignments 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.