先上代码

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的文件写入有最大字节数限制,所以一行一行写入。

java对象序列化并存储到文件中

● 如何将一个Java对象序列化到文件里 使用输入输出流,,一个是ObjectOutputStream 对象,ObjectOutputStream 负责向指定的流中写入序列化的对象.当从文件中读取序列 ...

lua的table表去重

推荐阅读:  我的CSDN  我的博客园  QQ群:704621321  我的个人博客 方法一 用过lua的人都知道,lua的table中不允许存在相同的key,利用这个思想,我们可以将原始table ...

Lua增加一个节点到文件中

新建一个文件touch /etc/config/ddns 增加一个节点到文件中uci set ddns.newadd=config :即配置文件,如ddns,ipv6等&l ...

Lua 多维表的遍历中的赋值

说到Lua的遍历将要使用到循环:先说遍历再说循环: 遇到这样类似结构的一个table Data={ []={p1=,pa={,,}}, []={p1=,pa={,,}}, []={p1=,pa={,, ...

关于 lua table表存储函数且运用

--table 是lua的一种数据结构用来帮助我们创建不同的数据类型.如:数组和字典--lua table 使用关联型数组,你可以用任意类型的值来做数组的索引,但这个值不能是nil--lua tabl ...

linux 进阶2--C++读取lua文件中的变量、一维表、二维表

lua 语言非常灵活,一般把lua 作为脚本文件,会用C++与之进行交互.最重要的是C++代码能读取到脚本中的变量.一维表.二维表. 这样有些参数就可以在lua文件进行更改,而不用重新更改C++代码. ...

树形打印lua table表

为方便调试lua程序,往往想以树的形式打印出一个table,以观其表内数据.以下罗列了三种种关于树形打印lua table的方法;法一 local print = print local tconca ...

[置顶] lua 进阶3--lua文件中调用C++函数

前面讲了一下,C++读取lua文件中的变量,包括一维表.二维表这些,这节讲一下如何在lua文件中去调用C++函数 C++代码如下 #include extern &qu ...

SQLLoader4(数据文件中的列与表中列不一致情况-filler)

A.数据文件中字段个数少于表中列字段个数,但数据文件中缺少的列,在表定义中可以为空.----- 这种情况是比较简单的,只需要将数据文件中数据对应的列的名字写到控制文件中即可.因为SQL*Loader是 ...