What is the scope of a Lua variable?
snippet in lua

What is the scope of a Lua variable?

user1082

local u = {
    f = function()
        -- Refers to the global variable `t` (that is, _ENV.t).
        -- Whenever the function is called, the *current* value of `t` is returned
        return t 
    end
}

print(u) -- prints table: 0xFOOBAR
print(u.f()) -- prints nil

t = u

print(t) --prints table: 0xFOOBAR
print(t.f()) --prints table: 0xFOOBAR

_ENV = {print = print}
print(u.f()) -- prints nil, since _ENV.t is now nil

local _ENV = {print = print, t = u}
print(u.f()) -- still prints nil, because the function definition used the
             -- _ENV variable that was lexically visible at the function definition,
             -- rather than the new _ENV variable that was just defined.