161218--lua学习 代码+笔记 基础篇2

来源:互联网 发布:网络狼人杀发言技巧 编辑:程序博客网 时间:2024/06/05 08:54

*************************
–文件的读写操作

 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();endwrite_content("namelist.txt","我是撇灬嚛")

*******************************************
–lua中的串行化

function serialize( o )    if type(o) =="number" then        io.write(o);    elseif type(o) == "string" then        io.write("[[",o,"]]")    endenda = " 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")    endendn_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")endreturn complex--另一文件m = require("take")m.showname()
1 0