Data文件:
- Entry{"Donald E. Knuth",
- "Literate Programming",
- "CSLI",
- 1992}
- Entry{"Jon Bentley",
- "More Programming Pearls",
- "Addison-Wesley",
- 1990}
读取文件数据:
- local count=0
- function Entry(b)
- count=count+1
- end
- dofile("oo.lua")
- print("number of entries:" .. count)
- -----------------------------------------------
- local authors={}
- function Entry(b)
- authors[b[1]]=true
- end
- dofile("oo.lua")
- for name in pairs(authors) do
- print(name)
- end
序列化:将数据转换为字节流或者字符流
- o={a=12,b="Lua",key="another one"}
- function serialize(o) --序列化serialize
- if type(o)=="number" then --number类型
- io.write(o)
- elseif type(o)=="string" then --string类型
- io.write(string.format("%q",o))
- elseif type(o)=="table" then --table类型
- for k,v in pairs(o) do
- io.write("[",k,"=")
- serialize(v)
- io.write("]\n")
- end
- io.write("\n")
- else
- error("cannot serialize a " .. type(o))
- end
- end
- serialize(o)
- ----------------------------------------------------------------------
- function basicSerialize(o)
- if type(o)=="number" then
- return tostring(o)
- else
- return string.format("%q",o)
- end
- end
- function save(name,value,saved)
- saved=saved or {}
- io.write(name,"=")
- if type(value)=="number" or type(value)=="string" then
- io.write(basicSerialize(value),"\n")
- elseif type(value)=="table" then
- if saved[value] then
- io.write(saved[value],"\n")
- else
- saved[value]=name
- io.write("{}\n")
- for k,v in pairs(value) do
- local filedname=string.format("%s[%s]",name,basicSerialize(k))
- save(filedname,v,saved)
- end
- end
- else
- error("cannot save a " .. type(value))
- end
- end
- a={x=1,y=2;{3,4,5}}
- a[2]=a
- a.z=a[1]
- save('a',a,t)
- a={{"one","two"},3}
- b={k=a[1]}
- local t={}
- save('a',a,t)
- save('b',b,t)