–*************************
–文件的读写操作
local f = assert(io.open("namelist.txt",'r'));
--r--读取权限,a 追加 w 写 b 打开二进制
local string = f:read("*all");--表示读取所有的文件内容
--*line表示读取一行,*number读取一个数字 <num>读取不超过num长度的字符长度
f:close();
print(string)
local f1 = assert(io.open("namelist.txt",'w'))--会覆盖
f1:write("\nIlovaeyou");
f1:close();
local function write_content( filename,content )
-- body
local f = assert(io.open(filename,'w'));
f:write(content)
f:close();
end
write_content("namelist.txt","我是撇灬嚛")
–*******************************************
–lua中的串行化
function serialize( o )
if type(o) =="number" then
io.write(o);
elseif type(o) == "string" then
io.write("[[",o,"]]")
end
end
a = " this is a lua program"
print(string.format("%q",a))
function n_serialize( o )
if type(o) == "number" then
io.write(o);
elseif type(o) == "string" then
io.write(string.format("%q",o));
elseif type(o) == "table" then
io.write("{\n")
for k,v in pairs(o) do
io.write(" ",k,"=")
n_serialize(v)--递归
io.write(",\n")
end
io.write("}\n")
end
end
n_serialize({123,"string"})
--输出
{
123,
string,
}
–***************************
–require
function showname( v )
print("mynameis===>"..v)
end
–假如在一个叫做aa.lua的文件中书写了如上函数 在另一lua文件中可以这样使用,此函数需要是全局的;
require ("aa")
showname("ls")
可以重新给io定义
local i = require("io")
i.write("ok\n")
路径的书写
--APP/test/a.lua
--require(app.test.a)
--[[
--reqire的执行过程
1.判断这个包是否存在;
2.判断是否加载
3.如果没有返回nil或者报错
4.反之,则返回对应的模块对象
]]
--在一个take.lua文件中书写
complex = {}
function complex.showname( )
print("hello lua")
end
return complex
--另一文件
m = require("take")
m.showname()