lua基础语法

来源:互联网 发布:中文语法分析常用算法 编辑:程序博客网 时间:2024/06/03 18:10

lua输入输出

--注释单行--,多行--[[ 到 ]] 结束--除了false和nil,其他表达式均为真,包括0和空串--字符串连接print('A bulb rated for 2200 hours will last ' .. (2200/6/365) .. ' years')--格式化输出print(('A bulb rated for %d hours will last about %.1f years'):format(2200, 2200/6/365))--变量直接赋值使用a = {"111", "222", "333"};print(a[1]);        --lua下标从1开始print(a[2]);print(a[3]);a[4] = 4;a[5] = 5;--两种循环输出for i, v in ipairs(a) do print(v) end -- 泛型for循环,i可省略for i = 1, 10, 1 do -- 数字for循环,第三个数为step,可以省略,默认为1    print(i);end;--两种循环语句i = 10;while i > 0 do    print(i);    i = i - 1;end;repeat    i = i + 1;    print(i);until i > 10;--ifelse语句if i > 0 then    print(i..">0")elseif i < 0 then    print("i < 0");else    print("i == 0");end--Lua语法要求break和return 只能出现在block的结尾一句,即chunk的最后一句,或者end之前,或者else前,或者until前--function add(function unpack(t, i) -- unpack返回a所有的元素作为f()的参数    i = i or 1    if t[i] then        return t[i], unpack(t, i + 1)    endendprint(unpack(a, 2))T1={    10,  -- 相当于 T1[1] = 10    [100] = 40,    John=  -- 如果你原意,你还可以写成:["John"] =    {        Age=27,   -- 如果你原意,你还可以写成:["Age"] =27        Gender=Male   -- 如果你原意,你还可以写成:["Gender"] =Male    },    20  -- 相当于 T1[2] = 20}print(unpack(T1, 1))print(T1[100])print(T1["John"]["Age"])--所有索引值都需要用"["和"]"括起来,如果不写索引,则索引会被认为是数字,按顺序自动从1往后编。T2 = {1, tom = 2, sai = 3, john = 4, 5}print(T2[2])--可变参数--local _, x = string.find(s, p)--x为find返回的第二个值print(string.find("hello hello", " hel"))   --> 6 9function select (n, ...)    return arg[n]endprint(select(1, string.find("hello hello", " hel")))     --> 6-- 10行、9列的矩阵mt = {}          -- create the matrixfor i = 1, 10 do    mt[i] = {}   -- create a new row    for j = 1, 9 do        mt[i][j] = 0    endend
0 0
原创粉丝点击