数据文件
借由table构造式来定义一种文件格式,数据写入时定义好格式,读取数据就会非常容易。这种技术也就是数据作为Lua代码来输出,但运行代码时,程序就读取了数据,table构造式可以使输出代码更像是一个普通的数据文件。
CSV数据格式
使用Lua中table的构造式作为格式,每条记录表示一个table构造式。
$ vim data
Entry{
"alice",
"female",
"alice@hotmail.com",
15526486071,
}
Entry{
"ben",
"male",
"ben@hotmail.com",
15526486072,
}
注意Entry{<code>}和Entry({<code>})是完全等价的,都是以一个table作为参数来调用函数Entry。
定义Entry函数读取数据文件
local count =0
local map = {}
function Entry(tbl)
count = count + 1
map[tbl[1]] = true
end
dofile("data")
-- TEST
print(count)
for k,v in pairs(map) do
print(k,v)
end
以上是采用事件驱动的做法,Entry函数作为一个回调函数,在dofile时为数据文件中的每个条目所调用。
自描述数据格式
若文件较少可采用名值对的方式来表示每个字段,又称为“自描述的数据格式(self-describing data)”,每项数据伴随一个表示其含义的简短描述。自描述数据格式比CSV或其它紧缩格式更具可读性。
$ vim data
Entry{
name = "alice",
gender = "female",
email = "alice@hotmail.com",
phone = 15526486071,
}
Entry{
name = "ben",
gender = "male",
email = "ben@hotmail.com",
phone = 15526486072,
}
local count =0
local map = {}
function Entry(tbl)
count = count + 1
if tbl.name then
map[tbl.name] = true
end
end
dofile("data")
-- TEST
print(count)
for k,v in pairs(map) do
print(k,v)
end
因此可见,自从Lua创建之初就将数据描述作为Lua的主要应用之一,因此开发人员能较快的编译大型程序投入。
串行化
需要串行化(Serialization)的数据一般是需要将数据转换为一个字节流或字符流,然后将其存储到文件中,或通过网络连接发送传输。串行化后的数据可用Lua代码来表示,当运行串行化的代码时,存储的数据可以在读取程序中进行重构。
-- 串行化
function serialize(var)
if type(var)=="number" then
io.write(var)
elseif type(var) == "string" then
-- 字符串值
-- io.write("'", var, "'")
-- 字符串中包含特殊字符(如引号、换行等)
-- io.write("[[", var, "]]")
-- 字符串中包含Lua可执行的命令时,如]]..os.execute('rm *')..[[
io.write(string.format("%q", var)) -- %q为转义字符
else
error("can not serialize variable "..type(var))
end
end

650

被折叠的 条评论
为什么被折叠?



