In lua, is there forward declaration?

Viewed 154

I wrote quite a lot of functions that call one another, in lua.

Is there, in lua, such a concept as "forward declaration" ?

That would allow me to declare all functions with no implementation and then implement them later. I would then get rid of the order of the functions problem.

2 Answers

yes the visibility goes from top to bottom. You can declare locals with no value.

local func -- Forward declaration. `local func = nil` is the same.

local function func2() -- Suppose you can't move this function lower.
    return func() -- used here
end

function func() -- defined here
    return 1
end

You can define your functions within a table.

local lib = {}

function lib.func2()
    return lib.func()
end

function lib.func()
    return 1
end

This minimizes the specific declaration needed at the top of the file. It does add a cost of indexing the table which may be relevant and is worth making note of.

This also exposes the functions if you were to return library, which may not be desired if some functions are intended to be "private" to the code in the file. in that case we can add a second table

local lib = {}
local private = {}

function lib.func2()
    return private.func()
end

function private.func()
    return 1
end

return lib
Related