Lua数据持久化

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)