lua中是否有前向声明?

In lua, is there forward declaration?

我在 lua.

中写了很多相互调用的函数

在lua中有没有“前向声明”这样的概念?

这样我就可以声明所有没有实现的函数,然后再实现它们。然后我会摆脱函数顺序问题。

是的,可见性从上到下。 您可以声明没有值的局部变量。

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

您可以在 table.

中定义您的函数
local lib = {}

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

function lib.func()
    return 1
end

这最大限度地减少了文件顶部所需的特定声明。 它确实增加了索引 table 的成本,这可能是相关的并且值得一提。

如果您要访问 return 库,这也会公开函数,如果某些函数打算对文件中的代码“私有”,则可能不需要这样做。在这种情况下,我们可以添加第二个 table

local lib = {}
local private = {}

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

function private.func()
    return 1
end

return lib