5

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
MrHappyAsthma
  • 6,332
  • 9
  • 48
  • 78

3 Answers3

8

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
finnw
  • 47,861
  • 24
  • 143
  • 221
8

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
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
5

Yes, it is legal. Lua handles local-variable declarations as statements.

Here's an interesting example from the Lua Reference Manual:

Notice that each execution of a local statement defines new local variables. Consider the following example:

 a = {}
 local x = 20
 for i=1,10 do
   local y = 0
   a[i] = function () y=y+1; return x+y end
 end

The loop creates ten closures (that is, ten instances of the anonymous function). Each of these closures uses a different y variable, while all of them share the same x.

In this example, if ignore the returning closure part, there are 10 local variables named y in the same for block.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294