I code therefore I am.

July 26, 2010 at 5:19pm
0 notes
Comments (View)
home

Tags:
Lua  

Swapping variable values using multiple assignment in Lua

Lua allows multiple assignment, where a list of values is assigned to a list of variables in one step. Both lists have their elements separated by commas. For instance, in the assignment

a, b = 10, 2*x

the variable a gets the value 10 and b gets 2*x.
In a multiple assignment, Lua first evaluates all values and only then executes the assignments. Therefore, we can use a multiple assignment to swap two values, as in

x, y = y, x -- swap `x' for `y'
a[i], a[j] = a[j], a[i] -- swap `a[i]' for `a[j]'

[Source: lua.org: 4.1 Assignment]

blog comments powered by Disqus