私は本から 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]] に :write しようとするとエラーになります。ここにリストされている前の 2 つの関数では、なぜそれらが _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