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?
Local variables help you avoid cluttering the global environment with unnecessary names. Moreover, the access to local variables is faster than to global ones. Lua handles local variable declarations as statements. As such, you can write local declarations anywhere you can write a statement.
In Lua, the preferred scope is local which you control by using the local declaration before you define a variable/function. For example: local someVariable. local function someFunction() end.
In Lua, though we don't have variable data types, we have three types based on the scope of the variable. Global variables − All variables are considered global unless explicitly declared as a local.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With