5

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?

asked Apr 26, 2016 at 15:58
1
  • 3
    lua is not javascript, it does not "hoist" variables. Commented Apr 26, 2016 at 16:30

2 Answers 2

5

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();
answered Apr 26, 2016 at 16:03
Sign up to request clarification or add additional context in comments.

3 Comments

"The scope of a local variable begins at the first statement after its declaration and lasts until the last non-void statement of the innermost block that includes the declaration." -- lua.org/manual/5.3/manual.html#3.5
Actually, only the 'local a' part needs to come first, as the value assigned to it may not be known yet. So, the assignment can still follow the definition of the inner function.
@tonypdmtr True, though that's why I said, "declared".
3

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.

answered Apr 26, 2016 at 19:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.