テーブルをテキストファイルに保存するには、テーブルをコンマ区切りのリストに変換する必要があります。Luaでこれを行うための組み込みのメソッドはありますか?
11137 次
5 に答える
15
テーブルが配列の場合、table.concat
CSV を印刷するために使用できます。
t={10,20,30}
print(table.concat(t,","))
出力します10,20,30
。
于 2011-07-06T00:00:19.160 に答える
2
組み込み関数はありませんが、Web上に例があります。
于 2011-07-05T22:43:04.667 に答える
1
いいえ、このための「組み込み」関数はありません。しかし、それを自分で行うのは難しくありません。LuaテーブルをLuaスクリプトとしてファイルに直接再帰的に書き込むためのスクリプトを保持しています。このスクリプトは、Luaスクリプトのようにロードして実行できます。
--This file exports a function, WriteTable, that writes a given table out to a given file handle.
local writeKey = {};
function writeKey.string(hFile, value, iRecursion)
WriteFormatted(hFile, "[\"%s\"]", value);
end
function writeKey.number(hFile, value, iRecursion)
WriteFormatted(hFile, "[%i]", value);
end
local writeValue = {};
function writeValue.string(hFile, value, iRecursion)
WriteFormatted(hFile, "[==[%s]==]", value);
end
function writeValue.number(hFile, value, iRecursion)
WriteFormatted(hFile, "%i", value);
end
function writeValue.boolean(hFile, value, iRecursion)
if(value) then hFile:write("true"); else hFile:write("false"); end;
end
function writeValue.table(hFile, value, iRecursion)
WriteTable(hFile, value, iRecursion)
end
local function WriteFormatted(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
local function WriteForm(hFile, strFormat, ...)
hFile:write(string.format(strFormat, ...));
end
local function WriteTabs(hFile, iRecursion)
for iCount = 1, iRecursion, 1 do
hFile:write("\t");
end
end
function WriteTable(hFile, outTable, iRecursion)
if(iRecursion == nil) then iRecursion = 1; end
hFile:write("{\n");
local bHasArray = false;
local arraySize = 0;
if(#outTable > 0) then bHasArray = true; arraySize = #outTable; end;
for key, value in pairs(outTable) do
if(writeKey[type(key)] == nil) then print("Malformed table key."); return; end
if(writeValue[type(value)] == nil) then
print( string.format("Bad value in table: key: '%s' value type '%s'.", key, type(value)));
return;
end
--If the key is not an array index, process it.
if((not bHasArray) or
(type(key) ~= "number") or
not((1 <= key) and (key <= arraySize))) then
WriteTabs(hFile, iRecursion);
writeKey[type(key)](hFile, key, iRecursion + 1);
hFile:write(" = ");
writeValue[type(value)](hFile, value, iRecursion + 1);
hFile:write(",\n");
end
end
if(bHasArray) then
for i, value in ipairs(outTable) do
WriteTabs(hFile, iRecursion);
writeValue[type(value)](hFile, value, iRecursion + 1);
hFile:write(",\n");
end
end
WriteTabs(hFile, iRecursion - 1);
hFile:write("}");
end
于 2011-07-05T22:40:50.630 に答える
0
組み込みの方法はありませんが、自分で構築したい場合は比較的簡単なオプションがいくつかあります。これがあなたがそれをどのようにまとめたいかを理解するのを助けることができるいくつかのリンクです:
http://www.lua.org/pil/12.1.html
http://lua-users.org/wiki/TableSerialization
于 2011-07-05T22:39:03.657 に答える