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?

spurra
  • 1,007
  • 2
  • 13
  • 38

2 Answers2

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();
canon
  • 40,609
  • 10
  • 73
  • 97
  • 6
    "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." -- http://www.lua.org/manual/5.3/manual.html#3.5 – Keith Thompson Apr 26 '16 at 16:19
  • 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 Apr 26 '16 at 20:31
  • @tonypdmtr True, though that's why I said, _"declared"_. – canon Apr 26 '16 at 20:38
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.

lhf
  • 70,581
  • 9
  • 108
  • 149