5

In the below code, could anyone please explain how b,a = a,b internally works?

-- Variable definition:
local a, b
-- Initialization
a = 10
b = 30

print("value of a:", a)

print("value of b:", b)

-- Swapping of variables
b, a = a, b
print("value of a:", a)

print("value of b:", b)
Prabhakar
  • 402
  • 6
  • 20
  • 1
    possible duplicate of [How does multiple assignment work?](http://stackoverflow.com/questions/15256516/how-does-multiple-assignment-work) – hjpotter92 Apr 11 '14 at 15:00

2 Answers2

14

Consider the Lua script:

local a, b
a = 10
b = 30
b, a = a, b

Run luac -l on it and you'll get this:

    1   [1] LOADNIL     0 1
    2   [2] LOADK       0 -1    ; 10
    3   [3] LOADK       1 -2    ; 30
    4   [4] MOVE        2 0
    5   [4] MOVE        0 1
    6   [4] MOVE        1 2
    7   [4] RETURN      0 1

These are the instructions of the Lua VM for the given script. The local variables are assigned to registers 0 and 1 and then register 2 is used for the swap, much like you'd do manually using a temporary variable. In fact, the Lua script below generates exactly the same VM code:

local a, b
a = 10
b = 30
local c=a; a=b; b=c

The only difference is that the compiler would reuse register 2 in the first case if the script was longer and more complex.

lhf
  • 70,581
  • 9
  • 108
  • 149
1

I assume that by internally you don't mean Lua C code?

Basically, in multiple assignment Lua always evaluates all expressions on the right hand side of the assignment before performing the assigment.

So if you use your variables on both side of the assigment, you can be sure that:

local x, y = 5, 10

x, y = doSomeCalc(y), doSomeCalc(x) --x and y retain their original values for both operations, before the assignment is made
W.B.
  • 5,445
  • 19
  • 29