Dus*_*ter 4 lua serialization lua-table
我想将2d lua表转换为字符串,然后将其转换为字符串后,使用新创建的字符串将其转换回表.好像这个过程被称为序列化,并在下面的url中讨论,但我很难理解代码,并希望有人在这里有一个简单的table.toString和table.fromString函数
http:// lua- users.org/wiki/TableSerialization
我使用以下代码来序列化表:
function serializeTable(val, name, skipnewlines, depth)
skipnewlines = skipnewlines or false
depth = depth or 0
local tmp = string.rep(" ", depth)
if name then tmp = tmp .. name .. " = " end
if type(val) == "table" then
tmp = tmp .. "{" .. (not skipnewlines and "\n" or "")
for k, v in pairs(val) do
tmp = tmp .. serializeTable(v, k, skipnewlines, depth + 1) .. "," .. (not skipnewlines and "\n" or "")
end
tmp = tmp .. string.rep(" ", depth) .. "}"
elseif type(val) == "number" then
tmp = tmp .. tostring(val)
elseif type(val) == "string" then
tmp = tmp .. string.format("%q", val)
elseif type(val) == "boolean" then
tmp = tmp .. (val and "true" or "false")
else
tmp = tmp .. "\"[inserializeable datatype:" .. type(val) .. "]\""
end
return tmp
end
Run Code Online (Sandbox Code Playgroud)
然后可以使用loadstring()执行创建的代码:http://www.lua.org/manual/5.1/manual.html#pdf-loadstring 如果您已经将参数传递给'name'参数(或者之后附加它) :
s = serializeTable({a = "foo", b = {c = 123, d = "foo"}})
print(s)
a = loadstring(s)()
Run Code Online (Sandbox Code Playgroud)
发布的代码lhf是一个比你链接的页面更简单的代码示例,所以希望你能更好地理解它.使其适应输出字符串而不是打印输出,如下所示:
t = {
{11,12,13},
{21,22,23},
}
local s = {"return {"}
for i=1,#t do
s[#s+1] = "{"
for j=1,#t[i] do
s[#s+1] = t[i][j]
s[#s+1] = ","
end
s[#s+1] = "},"
end
s[#s+1] = "}"
s = table.concat(s)
print(s)
Run Code Online (Sandbox Code Playgroud)
序列化的一般思想是从一些数据结构(如表)中获取所有数据位,然后循环遍历该数据结构,同时构建一个包含所有这些数据位以及格式化字符的字符串.
下kong作品这个
local cjson = require "cjson"
kong.log.debug(cjson.encode(some_table))
Run Code Online (Sandbox Code Playgroud)
出了kong应该安装lua-cjson包https://github.com/openresty/lua-cjson/
| 归档时间: |
|
| 查看次数: |
27885 次 |
| 最近记录: |