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

问题描述 投票:0回答:1

我编写了两个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。例如,我尝试通过ChapteroneModule.Chapter[1][1]访问每个模块中的twoModule.Chapter[2][1]变量,但它返回错误。

module lua
1个回答
0
投票

您提供的示例模块经过编码,因此不会对返回的表添加任何内容。

这导致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

您还可以简单地确保在模块中以及在模块中使用modOne.Chapter的任何地方都定义了Chapter

© www.soinside.com 2019 - 2024. All rights reserved.