lua-users home
lua-l archive

local scope once again

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi Everyone,
I am puzzled by the behaviour of the following code:
function foo()
 local x= 1
 local x= 20
 local x= 300
 local i=1
 while true do
 local name, value = debug.getlocal( 1, i)
 if not name then break end
 print("i=",i, "name=",name, "value=",value)
 i= i+1
 end
end
-- call the function
foo()
-- OUTPUT follows:
i= 1 name= x value= 1
i= 2 name= x value= 20
i= 3 name= x value= 300
i= 4 name= i value= 4
I am surprised to see that there are three different local 'x'
variables. All of them belong to the same "block" which is foo()
function body and, thus, should have the same scope. Why does not Lua
collapses them into just one local x variable??
--Leo--

AltStyle によって変換されたページ (->オリジナル) /