我需要将一个表格转换为逗号分隔的列表,以便将其保存到文本文件中。Lua 中是否有内置的方法可以实现此功能?
table.concat
来打印 CSV 文件:t={10,20,30}
print(table.concat(t,","))
输出 10,20,30
。
虽然 Lua 没有内置的函数,但是网上有很多示例。
不,这方面没有“内置”的功能。但是自己做起来也不难。我有一个脚本,可以递归地将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
虽然没有内置的方法,但如果您想自己构建它,有许多相对容易的选项可供选择。以下是一些链接,可以帮助您确定如何组合它:
http://www.lua.org/pil/12.1.html
http://lua-users.org/wiki/TableSerialization
是的,有一个内置方法,而且它已经存在很长时间了。
-- table.concat
local line = { "Fred", 20, 4.000 }
print(table.concat(line,","))