syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Lua how to multi assign?

Both Ruby and Python allow multiple assignment of variables.

So does Lua.

If I need to switch values between variables, multiple assignment allows me to collapse three lines of code into one:
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $ lua
Lua 5.3.0  Copyright (C) 1994-2015 Lua.org, PUC-Rio
>
> a = 1
> b = 2
> print(a,b)
1	2
>
> c = a
> a = b
> b = c
>
> print(a,b)
2	1
>
> a,b = b,a
> print(a,b)
1	2
>
>
dan@hp ~/ks/b/lua $
dan@hp ~/ks/b/lua $
In the above demo I want to switch the values of a and b. The first way I use intermediate variable c. That forces me to use three lines of code.

The second way uses Lua multiple assignment feature which allows me to switch the values with one line of code.

Another place I see multiple assignment is when I need to respond to a function which returns more than 1 value:
> function hello_world()
>> return 'hello', 'world'
>> end
>
> a,b = hello_world()
> a
hello
> b
world
>


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me