Search code examples
functionlualocal

Scope of local Lua functions


I'm a little confused regarding local functions in Lua. Please have a look at the following simplified example:

function test()
  local function f()
    print("f")
    g()
  end

  local function g()
    print("g")
  end

  f()
end

test()

Upon running this code, I get an error in function f, because function g is nil.

From my understanding, both functions should have been declared once the code reaches the call to function g. Since since both functions have not yet reached the end of the block (i.e. they're still within the function test), they should still be accessible. This code works fine when declaring the functions as global. So, I'm really not sure why it doesn't work with local functions. The book "Programming in Lua" didn't explain this behaviour either.


Solution

  • local function g() <BODY> end is equivalent local g; g=function () <BODY> end.

    In f, the name g is resolved a global because the local g appears after f has ended. This is what the error message tells us:

    attempt to call a nil value (global 'g')
    

    Try defining g before f.