functionluadeclarationdefinitions

Is there a way to put local functions in any order in Lua?


One thing that seems to set Lua apart from the languages I'm used to is that it's important what order you put variable and function declarations in. In a function, you can't access local variables that were declared after the function. For example:

local function foo()
 return bar
end
local bar = 4
print(foo()) -- prints nil instead of 4

The same is true if you're trying to access a local function from a function that's declared before it.

In some cases this can all work out if you're just careful about declaring things in the right order. But what if you have two or more functions that all need to call each other? Do the functions have to be global, or is there some way to do this with local functions?


Solution

  • Okay, I worked it out. It's just a matter of declaring things before you define them. I wasn't sure it would work with functions, but I should've known.

    local foo, bar
    function foo(a)
     print 'foo'
     if a == 3 then
      bar(4)
     end
    end
    function bar(b)
     print 'bar'
     if b == 4 then
      foo(2)
     end
    end
    foo(3)
    -- foo
    -- bar
    -- foo