先上**
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] = ;
endif 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
endfor 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))
endelse
if type(v) == "string" then
table.insert(tmp, key..'="'..v..'"');
else
table.insert(tmp, key.."="..tostring(v));
endend
endreturn "";
endreturn "do local ret=\n\n"..ser_table(t,"ret")..table.concat(assign," ").."\n\n return ret end"
endfunction 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
endtable.insert(arr, string.sub(str, pos))
return arr
endfunction 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");
endfile:close();
end
1、基礎功能抄自云風早期的**。 這裡稍微新增了排序功能,可以傳入排序函式,否則表是按雜湊排序的,輸出後會亂掉。
2、新增了writefile函式,因為lua的檔案寫入有最大位元組數限制,所以一行一行寫入。
序列化物件到檔案
資訊儲存在記憶體中是非常好的,但有時你的使用者不得不關閉你的應用程式。如果你想知道儲存在記憶體中是什麼資料,也就意味著 可能 你有時需要把資訊寫入檔案。今天,我們來看乙個 net 內建特徵叫做序列化 從檔案讀寫資料非常的容易。在這個例子中,我想建立乙個程式跟蹤所有有汽車的朋友。為了實現這個功能我建立...
lua序列化函式
此函式用來序列化table function serialze tbl,filename print filename file io.open filename,w if file nil then return end function serl tbl if type tbl number t...
C 序列化物件到檔案和從檔案發序列化物件
序列化物件和發序列化物件 程式應用過程中,經常會把物件序列化到到檔案中,以儲存資料。然後再從檔案中反序列化出來。具體應用如下 1,構造乙個類 注意一定要加上 serializable 表示可序列。serializable class parameter public string name publ...