我编写了两个lua
模块,每个模块中的每个变量名称都相同chapter
,但字符串不同。在主代码中,当我尝试打印所有章节时,即我将从不同的模块中获取这些章节并全部打印出来,只有最后加载的模块才打印其章节。
如何在主代码中的每个模块中访问章节变量?这是MWE:
第一个模块:
local modOne = {}
Chapter = {}
Chapter[1] = {chapNum = 1}
Chapter[1][1] = "This is the first verse of the modOne"
Chapter[1][2] = "This is the second verse of the modOne"
Chapter[2] = {chapNum = 2}
Chapter[2][1] = "This is the third verse of the modOne"
Chapter[2][2] = "This is the fourth verse of the modOne"
return modOne
第二模块:
local modTwo = {}
Chapter = {}
Chapter[1] = {chapNum = 1}
Chapter[1][1] = "This is the first verse of the modTwo"
Chapter[1][2] = "This is the second verse of the modTwo"
Chapter[2] = {chapNum = 2}
Chapter[2][1] = "This is the third verse of the modTwo"
Chapter[2][2] = "This is the fourth verse of the 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
。例如,我尝试通过Chapter
或oneModule.Chapter[1][1]
访问每个模块中的twoModule.Chapter[2][1]
变量,但它返回错误。
您提供的示例模块经过编码,因此不会对返回的表添加任何内容。
这导致Chapter
是一个全局变量,由第一个模块创建,然后由第二个模块更改。
要更正此问题,模块应写成:
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
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
您还可以简单地确保在模块中以及在模块中使用modOne.Chapter
的任何地方都定义了Chapter
。