使用彼此本地对象的模块

标签 module lua local

在 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 block 中。

它也是 - 表格内的所有表格以及每个大括号和缩进的换行符等等 - 相当长。所以我想把它放在自己的模块中,但是然后它无法访问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
    }
    ...
}

我真的不知道该怎么做。

有没有一种方法可以将变量从所需文件传递到所需文件,而不涉及将变量插入全局命名空间?

最佳答案

主模块:

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

关于使用彼此本地对象的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38702063/

相关文章:

mysql - 即使使用 --local-infile=1 也无法将大 CSV 导入 MySQL 5.6

go - 如何从相对本地文件夹导入 "include"意义上的 .go 文件

java - 设置Heroku模板java应用程序的开发环境

javascript - 需要自定义模块的问题

module - 无法在 GNU 序言中加载库(readutil)模块?

lua - 如何在lua类中编写私有(private)函数

lua - 为什么将参数传递给 lua 类方法得到 nill

http - 我的 GET 请求有什么问题?

.NET混合多文件程序集

linux - 内核模块(.ko 文件)移植到 DLL 导出符号