Reputation: 506
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.
Upvotes: 5
Views: 603
Reputation: 5021
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 lib
, 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 private
which will be encapsulated at the local scope:
local lib = {}
local private = {}
function lib.func2()
return private.func()
end
function private.func()
return 1
end
return lib
Upvotes: 3
Reputation: 1762
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
Upvotes: 6