Lua:何时以及如何将表写入_G中

我正在从一本书中学习 Lua,但我不是程序员。我试图使用以下函数(直接从书中复制而来)将一张数据表保存到一个文件中,但当尝试从 _G[resTable] 获取字符串时,该函数会出现错误。为什么?

function readFromFile(filename, resTable)
    local hfile = io.open(filename)
    if hfile == nil then return end
    local results = {} - 为什么这里有一张表?
    local a = 1
    for line in hfile:lines() do-- 调试显示该循环未运行(hfile 中没有行)
        _G[resTable[a]] = line
        a = a + 1
    end
end

function writeToFile(filename, resTable)
    local hfile = io.open(filename, "w")
    if hfile == nil then return end
    local i
    for i = 1, #resTable do
        hfile:write(_G[resTable[i]]) -- bad argument #1 to 'write' (string expected, got nil)
    end
end

当尝试对 _G[resTable[i]] 进行 :write 时,“writeToFile”会出现错误。在这里列出的两个先前的函数中,我不明白为什么他们在引用 _G[resTable[i]],因为我没有看到任何写入到 _G 的代码。

因此,这是执行顺序:

local aryTable = {
"Score",
"Lives",
"Health",
}

readFromFile("datafile", aryTable)

writeToFile("datafile", aryTable)

我得到了一个错误:

bad argument #1 to 'write' (string expected, got nil)
stack traceback:
[C]: in function 'write'
test.lua:45: in function 'writeToFile'
test.lua:82: in main chunk

点赞
用户1824182
用户1824182

那些不是广义的“从/到任何文件读/写任何表格”的函数。 显然,它们希望把一个全局表格的名称作为参数,而不是一个表格本身的引用。 它们看起来像是针对非常具体问题的一次性解决方案,通常会出现在书籍中。 :-)

你的函数不应该对_G做任何操作。 我没有一个API参考资料在手边,但读循环应该做类似这样的事情:

resTable [a] = line

写循环将是这样的:

hfile:write(resTable [i])

也可以扔掉那个名为“results”的局部表格。 :-)

2013-10-10 20:04:10
用户189205
用户189205

这段代码从文件中读取和写入数据到名为 aryTable 的全局变量中。由于你的文件是空的,readFromFile 没有真正设置变量值。然后,在获取变量值时,writeToFile 失败,因为它们还没有被设置。

尝试向文件中添加数据,以便变量得到设置,或在将其写入文件之前自己设置变量值(例如,Score = 10等)。

2013-10-10 20:37:23