在用lua做游戏开发的时候,需要本地的保存一些游戏的数据,以便在玩家登录游戏的时候,同步上次登录的状态信息,那么就涉及到把游戏中的数据保存在本地,接下来就对lua中的读写文件做一个总结:
1.打开文件
io.open (fn [, m]) 打开文件,返回文件句柄,fn文件名,m模式有:
r 以只读方式打开文件,该文件必须存在。
w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会消失。若文件不存在则建立该文件。
a 以附加的方式打开只写文件。若文件不存在,则会建立该文件,如果文件存在,写入的数据会被加到文件尾,即文件原先的内容会被保留。(EOF符保留)
r+ 以可读写方式打开文件,该文件必须存在。
w+ 打开可读写文件,若文件存在则文件长度清为零,即该文件内容会消失。若文件不存在则建立该文件。
a+ 与a类似,但此文件可读可写
b 二进制模式,如果文件是二进制文件,可以加上b
+ 号表示对文件既可以读也可以写
local fn = io.open(file,"r") --以只读的方式打开文件,如果文件不存在,则为nil
local fn1 = io.open(file,"w") --以只写的方式打开文件
2.关闭文件
local fn = io.open(file,"r") --以只读的方式打开文件
fn:close() --关闭上面打开的文件
3.读取文件
local fn = io.open(file,"r") --以只读的方式打开文件
if not fn then return end
local t = fn:read("*all") --读取文件
if t then
local fc = loadstring(t)
if fc ~= nil then
fc()
end
end
--fn:read()有以下几种方式:
--"*all" 读取整个文件
--"*line" 读取下一行
--"*number" 从串中转换出一个数值
4.写文件
local fn = io.open(file,"w") --以只读的方式打开文件
if not fn then return end --判断文件是否存在
fn:write(string.format("user=%q\n", user)) --写入东西
fn:write("hello world")
fn:close() --写入完毕之后,关闭文件
注意:
--读文件(三步骤:打开文件,读文件,关闭文件)
local fn = io.open(file,"r")
local t = fn:read("*all")
f:close()
--写文件(三步骤:打开文件,写文件,关闭文件)
local fn = io.open(file,"w")
fn:write("hello world")
f:close()
话说loadstring函数
Lua中还提供了另外一种动态执行Lua代码的方式,即loadstring函数。顾名思义,相比于loadfile,loadstring的代码源来自于其参数中的字符串,如:
f = loadstring(“i = i + 1”) --等价于 function f() i = i + 1 end
i = 0
f()
print(i) --将输出1
f()
print(i) --将输出2
对于loadstring返回的函数,如果需要对一个表达式求值,则必须在其之前添加return,这样才能构成一条语句,返回表达式的值,如
i = 32
f = loadstring("i = i + 1; return i * 2")
print(f()) --输出66
print(f()) --输出68。由于loadstring返回的就是正规的函数,因此可以被反复调用。