我正在从一本书中学习 Lua,我不是程序员。我正在尝试使用以下函数(直接从书中复制)将数据表保存到文件中,但是在尝试从 _G[resTable] 获取字符串时,该函数出现错误。为什么?
function readFromFile(filename,resTable)
local hfile = io.open(filename)
if hfile == nil then return end
local results = {} -why is this table here?
local a = 1
for line in hfile:lines() do-- debug shows this loop doesn't run (no lines in 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
“writeToFile”在尝试写入 _G[resTable[i]] 时出错。在此处列出的前两个函数中,我不明白为什么它们引用 _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