Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does swapping of variable works in Lua?

Tags:

lua

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)
like image 408
Prabhakar Avatar asked Apr 11 '14 07:04

Prabhakar


2 Answers

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.

like image 97
lhf Avatar answered Sep 27 '22 18:09

lhf


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
like image 22
W.B. Avatar answered Sep 27 '22 19:09

W.B.