Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - Two local variables with the same name

I have been learning Lua and I was wondering if it is allowed to reference two local variables of the same name.

For example, in the following code segment, is the syntax legal (without undefined behavior)?

I ask because it does run, but I cannot seem to figure out what is happening behind the scenes. Is this simply referencing the same x local? Or are there now two local x variables that mess things up behind the scenes. I'd like to know what exactly is happening here and why it is the case.

local x = 5 + 3; -- = 8
local x = 3 - 2; -- = 1

print("x = " .. x); -- x = 1
like image 538
MrHappyAsthma Avatar asked Jun 06 '13 13:06

MrHappyAsthma


2 Answers

There are two variables. The second shadows (but does not remove or overwrite) the first.

Sometimes you can still access the earlier definition via a closure.

local x = 5 + 3
local function getX1()
  return x
end
local x = 3 - 2
local function getX2()
  return x
end

print("x = " .. x); -- x = 1
print("x = " .. getX1()); -- x = 8
print("x = " .. getX2()); -- x = 1
like image 114
finnw Avatar answered Oct 01 '22 12:10

finnw


All your local variables have been remembered by Lua :-)

local x = 5 + 3; -- = 8
local x = 3 - 2; -- = 1

local i = 0
repeat
   i = i + 1
   local name, value = debug.getlocal(1, i)
   if name == 'x' then
      print(name..' = '..value)
   end
until not name
like image 42
Egor Skriptunoff Avatar answered Oct 01 '22 13:10

Egor Skriptunoff