Assignment Tutorial |
|
Setting the value of a variable is an assignment:
> x = 1 > y = "hello" > print(x,y) 1 hello
In Lua we can can perform multiple assignments in a single statement, e.g.,
> x, y = 2, "there" > print(x,y) 2 there
=. We can assign as many values as we like and they don't all have to be of the same type. e.g.,
> a,b,c,d,e,f = 1,"two",3,3.14159,"foo",{ this="a table" } > print(a,b,c,d,e,f) 1 two 3 3.14159 foo table: 0035BED8
Values on the right of the equal sign can be expressions, like i+1, but values on the left side cannot.
Multiple assignment comes with a few caveats as described below.
Any expressions are evaluated first. The evaluated expression is then assigned.
> i = 7
> i, x = i+1, i
> print(i, x)
8 7
When Lua reaches the second line, it evaluates the expressions i+1 and i before anything else. After evaluation, second line becomes i, x = 8, 7. Then it performs the assignments right to left. (see below for assignment order)
Because values are assigned as though all assignments are simultaneous, you can use multiple assignment to swap variable values around.
> a,b = 1,2 -- set initial values > print(a,b) 1 2 > a,b = b,a -- swap values around > print(a,b) 2 1 > a,b = b,a -- and back again > print(a,b) 1 2
bold = b; b = a; a = bold;), as would typically be used in the C language.
The order in which multiple assignments are performed is not defined. This means you should not assume that the assignments are made left to right; if the same variable or table reference occurs twice in the assignment list, you may be surprised by the results.
> a, a = 1, 2
> print(a)
1
a=2 and then a=1, but we should not depend on this being consistent in future versions of Lua. If the order of assignment is important, you should use separate assignment statements.
In particular, watch out for statements like the following. If i==j, these two statements can do different things:
> table[i], table[j] = table[j], table[k] > table[j], table[i] = table[k], table[j]
> table[i], table[j] = table[j], table[i]
If a value list is longer than the variable list the extra values are ignored.
> a,b,c = 1,2,3,4,5,6
> print(a,b,c)
1 2 3
If a value list is shorter than the variable list Lua assigns the value nil to the variables without a value.
> a,b,c,d = 1,2 > print(a,b,c,d) 1 2 nil nil