1、數據文件
我們可以利用Lua中的table構造式來定義一種文件格式,即文件中的數據是table構造並初始化的代碼 ,這種方式對於Lua程序而言是非常方便和清晰的,如:
Entry{"deng","Male","22"}
Entry{"li","Female","22"}
該數據存儲在“example.lua”文件中
需要注意的是,Entry{<code>}等價於Entry({code}),對於上面的數據條目,如果我們能夠定義一個合適的Entry函數,就能讓這些數據成為Lua代碼的一部分了。
local count=0 --這里預先定義Entry函數,以便執行dofile時能找到匹配的函數 function Entry() count =count+1 end dofile("example.lua") print(count) --輸出結果 --2
還有一種更清晰詳細的自描述表達形式
Entry{name="deng",sex="Male",age="22"}
Entry{name="li",sex="Female",age="22"}
該數據存儲在“example.lua”文件中
personInfo={} function Entry(s) if s.name then personInfo[s.name]=true end end dofile("example.lua") for name in pairs(personInfo) do print(name) end --輸出結果 --deng --li
從上可以看出,Entry作為回調函數,執行dofile文件時為文件中的每條目錄所調用。
lua不僅運行快,而且編譯也快,這主要是因為在設計之初就將數據描述作為lua的主要應用之一。
2、序列化
序列化通俗一點的解釋,就是將數據對象轉換為字節流再通過IO輸出到文件或者網絡,讀取的時候再將這些數據重新構造為與原始對象具有相同值得新對象。
Info={ { name="Deng" ,sex="Male", age="22"}, { name="Li", sex="Female", age="22"} } function toSerial(s) if type(s)=="number" then io.write(s) elseif type(s)=="string" then io.write(string.format("%q",s)) elseif type(s)=="table" then io.write('{\n') for i, v in pairs(s) do io.write('[') toSerial(i) io.write(']=') toSerial(v) io.write(',\n') end io.write('}\n') end end toSerial(Info)