PHa*_*zer 7 lua global-variables lua-table
我正在从书中学习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
Run Code Online (Sandbox Code Playgroud)
'writeToFile'在尝试执行以下操作时出错:写入_G [resTable [i]].在此处列出的前两个函数中,我不明白他们为什么引用_G [resTable [i]],因为我看不到任何写入_G的代码.
所以这是执行的顺序:
local aryTable = {
"Score",
"Lives",
"Health",
}
readFromFile("datafile", aryTable)
writeToFile("datafile", aryTable)
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
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
Run Code Online (Sandbox Code Playgroud)
这些不是通用的“从任何文件读取任何表或向任何文件写入任何表”功能。他们显然期望全局表的名称作为参数,而不是[对本地]表本身的引用。它们看起来像是书本上经常出现的针对某个非常具体问题的一次性解决方案。:-)
您的函数不应该对 _G 执行任何操作。我没有方便的 API 参考,但读取循环应该做类似的事情
resTable[a] = line
Run Code Online (Sandbox Code Playgroud)
写循环会做
hfile:write(resTable[i])
Run Code Online (Sandbox Code Playgroud)
也扔掉本地“结果”表。:-)