Redeclaring variable using the same name is legal in Lua?

Viewed 244

I'm a newbie in Lua and I just found out the following code is legal in Lua.

local abc = 123
local abc = 345
print(abc)

Is there any difference between the above and the following?

local abc = 123 
abc = 345
print(abc)
2 Answers

Each execution of a local statement defines new local variables check this both variables have a separate identity but using the same name will hide the first one

local abc =  123
local function abc1()
  print(abc)
end

local abc = 345
local function abc2()
  print(abc)
end

print(abc1()) -- 123
print(abc2()) -- 345

There is a difference. The first code has two local variables whereas the second one has only one. This can be detected using the debug library for instance. Compare the output of luac -l on both scripts.

Related