我目前使用的是这个函数:我有一个函数,它接受多维表格并将其转换为字符串。格式就像lua代码中的表格一样。现在我必须反转它--目标是得到相同的多维表。我发现了这个从表中获取字符串的函数--反之亦然?
toReturn = "{"
for ind, val in pairs(tbl) do
if type(val) == "table" then
toReturn = toReturn .. (type(ind) == "number" and "" or ind .. "=") .. tableAsString(val) .. ","
else
local newVal
if type(val) == "string" then
newVal = "\"" .. val .. "\""
else
newVal = val
end
toReturn = toReturn .. (type(ind) == "number" and "" or ind .. "=") .. newVal .. ","
end
end
toReturn = toReturn:sub(1,-2) .. "}" -- remove trailing "," and close table
return toReturn
end
发布于 2020-01-14 06:02:09
Nifim的答案很好用,我的问题也解决了。可以使用以下命令读取该表
loadstring(serializedTable)()
再次感谢!
发布于 2020-01-14 23:34:31
您的表还可以包含字符串"
、换行符、制表符等。我为自己编写了此函数,它负责以下操作:
local function buildLiteral(value, tableAsVararg, buildedLiteralsCache)
if not buildedLiteralsCache then
buildedLiteralsCache = {}
end
local resultStr = nil
if value == nil then
resultStr = "nil"
else
if not buildedLiteralsCache[value] then
local t = type(value)
local str = nil
if t == "boolean" or t == "number" then
str = tostring(value)
elseif t == "string" then
str = "\"" .. string.gsub(string.gsub(string.gsub(string.gsub(string.gsub(value, "\\", "\\\\"), "\"", "\\\""), "\r", "\\r"), "\n", "\\n"), "\t", "\\t") .. "\""
elseif t == "table" then
if tableAsVararg then
str = ""
if table.getn(value) >= 1 then
for _, v in ipairs(value) do
str = str .. buildLiteral(v, false, buildedLiteralsCache) .. ", "
end
str = string.sub(str, 1, string.len(str) - 2)
end
else
str = "{"
for k, v in pairs(value) do
str = str .. "[" .. buildLiteral(k, false, buildedLiteralsCache) .. "]=" .. buildLiteral(v, false, buildedLiteralsCache) .. ", "
end
if string.len(str) > 1 then
str = string.sub(str, 1, string.len(str) - 2)
end
str = str .. "}"
end
else
error("buildLiteral called with unsupported type='" .. t .. "'")
end
buildedLiteralsCache[value] = str
end
resultStr = buildedLiteralsCache[value]
end
return resultStr
end
然后,可以使用loadstring(str)()
再次装入该表
https://stackoverflow.com/questions/59708029
复制相似问题