我正在从一本书中学习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
当尝试向_G[resTable[i]]写入时,“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
readFromFile
做什么? - interjaywriteToFile
函数无法将数据写入文件,因此readToFile
函数当然读取到了 nil。 - PHazer