不同模块文件中相同变量名总是返回最后一个的问题

我编写了两个 lua 模块,每个模块中都有相同变量名 chapter,但是字符串不同。在主代码中,当我尝试打印所有章节,即从不同模块获取章节并将它们全部打印出来时,只有最后加载的模块可以打印它的章节。

如何在主代码中访问每个模块中的章节变量?以下为 MWE:

第一个模块:

local modOne = {}

Chapter = {}
    Chapter[1] = {chapNum = 1}
        Chapter[1][1] = "这是 modOne 的第一节"
        Chapter[1][2] = "这是 modOne 的第二节"
    Chapter[2] = {chapNum = 2}
        Chapter[2][1] = "这是 modOne 的第三节"
        Chapter[2][2] = "这是 modOne 的第四节"

return modOne

第二个模块:

local modTwo = {}

Chapter = {}
    Chapter[1] = {chapNum = 1}
        Chapter[1][1] = "这是 modTwo 的第一节"
        Chapter[1][2] = "这是 modTwo 的第二节"
    Chapter[2] = {chapNum = 2}
        Chapter[2][1] = "这是 modTwo 的第三节"
        Chapter[2][2] = "这是 modTwo 的第四节"

return modTwo

主代码:

oneModule = require('modOne')
twoModule = require('modTwo')

for i = 1, #Chapter do
    for j = 1, #Chapter[i] do
        print(Chapter[i][j])
    end
end

代码总是读取最后加载的 Chapter 变量,但我想选择打印哪个 Chapter。我尝试通过 oneModule.Chapter [1] [1]twoModule.Chapter [2] [1] 访问每个模块中的 Chapter 变量,但它返回错误。

点赞
用户7396148
用户7396148

你提供的示例模块的代码没有向返回的表中添加任何内容。

这将导致Chapter成为全局变量,由第一个模块创建,然后由第二个模块更改。

为了纠正这个问题,应该这样编写这些模块:

modOne:

local modOne = {
    Chapter = {
        [1] = {
            chapNum = 1,
            [1] = "This is the first verse of the modOne",
            [2] = "This is the second verse of the modOne",
        },
        [2] = {
            chapNum = 2,
            [1] = "This is the third verse of the modOne",
            [2] = "This is the fourth verse of the modOne",
        }
    }
}
return modOne

modTwo:

local modTwo = {
    Chapter = {
        [1] = {
            chapNum = 1,
            [1] = "This is the first verse of the modTwo",
            [2] = "This is the second verse of the modTwo",
        },
        [2] = {
            chapNum = 2,
            [1] = "This is the third verse of the modTwo",
            [2] = "This is the fourth verse of the modTwo",
        }
    }
}
return modTwo

主代码:

oneModule = require('modOne')
twoModule = require('modTwo')

for i = 1, #oneModule.Chapter do
    for j = 1, #oneModule.Chapter[i] do
        print(oneModule.Chapter[i][j])
    end
end
for i = 1, #twoModule.Chapter do
    for j = 1, #twoModule.Chapter[i] do
        print(twoModule.Chapter[i][j])
    end
end

您也可以简单地确保在定义模块中的Chapter和在模块中使用它的每个地方时均使用modOne.Chapter

2020-01-06 17:48:09