【问题标题】:Modules using each other's local objects模块使用彼此的本地对象
【发布时间】:2023-03-03 01:40:01
【问题描述】:

在 vanilla Lua 5.2 中,我有一个模块,其中包含:

  • 两个本地函数,A 和 B:B 会一直调用 A,A 有时会调用 B,有时会调用 C 中存储的函数;

  • C:一个表(本地)。它包含包含表的表,其中包含可以包含表的表......最后将包含函数。这些函数可能调用 A 或 B;

  • 然后是返回函数 D,当我使用 require 加载我的模块时将返回该函数。它会调用 A。

最后,它看起来很像这样:

--don't pay attention to what the functions do:
--I am only writing them down to explain how they interact with each other

local A, B, C

C = {
    ...
    {
        function(a)
            B(a)
         end
    }
    ...
}

A = function(a)
    ...
    if (...) then
        B(a)
    end
    ...
    if (...) then
        C[...]...[...](a)
    end
    ...
end

B = function(a)
    A(a)
end

return function(s) -- we called this one D
    A(s)
end

现在,我的问题是:C 的声明使用它自己的局部变量、元表和所有这些东西,以至于我将它的声明包含在 do ... end 块中。

它也是 - 所有这些表格都在表格中,每个大括号和缩进等换行符 - 相当长。所以我想把它放在自己的模块中,但是它无法访问B。

所以,我的问题是:有没有办法将 B 甚至 A 传递给在加载时声明 C 的文件?如果可能的话,我的意思是这样的:

--in the original module
local A, B, C

C = require("c", A, B)

...

然后,在 c.lua 中:

local A, B = select(1, ...), select(2, ...)

C = {
    ...
    {
        function(a)
            B(a)
        end
    }
    ...
}

我真的不知道该怎么做。

有没有办法将变量从需求文件传递到所需文件,而不涉及插入全局命名空间中的变量?

【问题讨论】:

    标签: module lua local


    【解决方案1】:

    主模块:

    local A, B, C
    
    A = function(a)
        ...
        if (...) then
            B(a)
        end
        ...
        if (...) then
            C[...]...[...](a)
        end
        ...
    end
    
    B = function(a)
        A(a)
    end
    
    C = require("c")(A, B)
    
    return function(s) -- we called this one D
        A(s)
    end
    

    c.lua:

    local function C_constructor(A, B)
        local C = 
            {
                ...
                {
                    function(a)
                        B(a)
                    end
                }
                ...
            }
        return C
    end
    
    return C_constructor
    

    【讨论】:

    • 这很聪明,真的很聪明。
    【解决方案2】:

    有没有办法将变量从需求文件传递到所需文件,而不涉及插入全局命名空间中的变量?

    不使用默认的require 函数,但这不应该阻止您编写自己的require 函数来执行此操作。显然,这将使解决方案特定于您的应用程序,因此当使用标准 Lua 解释器(及其require 函数)时,这些所需文件将无法正常运行。

    【讨论】:

    • 这实际上阻止我哈哈。我实际上并没有编写一个独立的应用程序,我有一天会将整个代码库转换为 C 或 C++,那何必呢?
    猜你喜欢
    • 2017-12-28
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多