Formatted code
local function A()
warn(foo1)
end
foo1 = 5
A() --> 5
local B = function()
warn(foo2)
warn(getfenv().foo2)
end
local foo2 = 10
B()
--[[
if foo2 is local:
--> nil nil
if foo2 is global:
--> 10 10
]]
As the lua documentation explains, “the scope of a local variable […] lasts until the last non-void statement of the innermost block that includes the declaration”. (Source: Lua 5.3 Reference Manual)
Therefore, in simpler terms, a variable declared in a script evironment (outside functions, do-blocks, and similar limited scopes) will be accessible anywhere after the declaration.
print(a) --> nil (unless a is a global variable)
local a = true
print(a) --> true
A variable declared without the keyword local
is a global variable accessible anywhere in the script context, but comes at a cost of worse performance. Local variables are always faster to work with.
A function, no matter how it’s defined, is also referenced by a variable - its name.
local function fn() end
local fn = function() end
Provided that a function is referenced in a global variable, e.g. function fn() end
, it can even be accessed by functions defined earlier in the script (which wouldn’t be possible if it was local).
local function fn1(arg) fn2("something") end
function fn2(arg) print(arg) end --> a local function would error
fn1() --> something
Now, getfenv()
has the capacity to access other environments, for instance the environment wherever the function that used getfenv()
was called. It was recently deprecated and causes deoptimisations because the compiler has to treat functions that use it as impure.
Edit. @swag4lifex sorry, didn’t see your last reply before posting. Tl;dr: there shouldn’t be any difference. Perhaps the error was thrown because of a typo.