lua序列化table表到文件中
2024-08-24 18:14:10
先上代码
function luautil.serialize(t, sort_parent, sort_child)
local mark={}
local assign={} local function ser_table(tbl,parent)
mark[tbl]=parent
local tmp={}
local sortList = {};
for k,v in pairs(tbl) do
sortList[#sortList + 1] = {key=k, value=v};
end if tostring(parent) == "ret" then
if sort_parent then table.sort(sortList, sort_parent); end
else
if sort_child then table.sort(sortList, sort_child); end
end for i = 1, #sortList do
local info = sortList[i];
local k = info.key;
local v = info.value;
local key= type(k)=="number" and "["..k.."]" or k;
if type(v)=="table" then
local dotkey= parent..(type(k)=="number" and key or "."..key)
if mark[v] then
table.insert(assign,dotkey.."="..mark[v])
else
table.insert(tmp, "\n"..key.."="..ser_table(v,dotkey))
end
else
if type(v) == "string" then
table.insert(tmp, key..'="'..v..'"');
else
table.insert(tmp, key.."="..tostring(v));
end
end
end return "{"..table.concat(tmp,",").."}";
end return "do local ret=\n\n"..ser_table(t,"ret")..table.concat(assign," ").."\n\n return ret end"
end function luautil.split(str, delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(str, delimiter, pos, true) end do
table.insert(arr, string.sub(str, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(str, pos))
return arr
end function luautil.writefile(str, file)
os.remove(file);
local file=io.open(file,"ab"); local len = string.len(str);
local tbl = luautil.split(str, "\n");
for i = 1, #tbl do
file:write(tbl[i].."\n");
end
file:close();
end
1、基础功能抄自云风早期的代码。 这里稍微添加了排序功能,可以传入排序函数,否则表是按哈希排序的,输出后会乱掉。
2、添加了writefile函数,因为lua的文件写入有最大字节数限制,所以一行一行写入。
最新文章
- CentOS下开启mysql远程连接,远程管理数据库
- idea使用心得(3)-重构初探
- js错误:对象不支持此属性或方法
- Winxp下搭建SVN服务器
- java内存模型 年轻代/年老代 持久区
- boost之ThreadPool
- iOS开发之动画编程的几种方法
- 用sp_change_users_login消除Sql Server的孤立用户
- 找到程序真正的入口(使用IDE追踪)
- freemarker 集成 sitemesh 装饰html页面 shiro 标签
- Git团队协作之GitFlow &; SoucceTree
- 将Maple输出的LaTex导出到txt文件
- 激活函数——tanh函数(理解)
- 【CF1141G】Privatization of Roads in Treeland
- LG1337 [JSOI2004]平衡点 / 吊打XXX
- 【逆向工具】IDA使用3-全局变量、数组、结构体
- psql: could not connect to server: No such file or directory&;&;PGHOST
- php RSA加密传输代码示例(轉)
- [z]libevent入门教程:Echo Server based on libevent 不指定
- 修改linux的时间可以使用date指令