I have the following function
function test()
local function test2()
print(a)
end
local a = 1
test2()
end
test()
This prints out nil
The following script
local a = 1
function test()
local function test2()
print(a)
end
test2()
end
test()
prints out 1.
I do not understand this. I thought declaring a local variable makes it valid in its entire block. Since the variable 'a' is declared in the test()-function scope, and the test2()-function is declared in the same scope, why does not test2() have access to test() local variable?
-
3lua is not javascript, it does not "hoist" variables.Etan Reisner– Etan Reisner2016年04月26日 16:30:12 +00:00Commented Apr 26, 2016 at 16:30
2 Answers 2
test2 has has access to variables which have already been declared. Order matters. So, declare a before test2:
function test()
local a; -- same scope, declared first
local function test2()
print(a);
end
a = 1;
test2(); -- prints 1
end
test();
3 Comments
You get nil in the first example because no declaration for a has been seen when a is used and so the compiler declares a to be a global. Setting a right before calling test will work. But it won't if you declare a as local.