LUA 拾遗(表的构造、流程控制)

本文深入探讨了Lua编程语言的基本概念,包括表的构造、流程控制(如if、while、for循环)以及记录风格的使用。文章通过具体实例展示了如何在Lua中进行变量赋值、函数调用和条件判断等操作。

一、表的构造

(list 风格)
    days = { "Sunday" , "Monday" , "Tuesday", "Wednesday", 
         "Thursday" , "Friday" , "Saturday" } 
    Lua 将"Sunday" 初始化days[1](第一个元素索引为 1),用"Monday"初始化days[2]...

    w = {x=0, y=0, label="console"} 
    x = {sin(0), sin(1), sin(2)} 
    w[1] = "another field"  
    x.f = w 
    print(w[ "x" ])   --> 0 
    print(w[1])   --> another field 
    print(x.f[1])   --> another field 
    w.x = nil      -- remove field "x" 

(record 风格)
    opnames = {["+" ] = "add" , [ "-" ] = "sub" , 
        ["*" ] = "mul" , [ "/" ] = "div" } 

    i = 20; s = "-"  
    a = {[i+0] = s, [i+1] = s..s, [i+2] = s..s..s} 
 
    print(opnames[s])   --> sub 
    print(a[22])     --> --- 



二、流程控制
(if)
    if conditions then  
        then-part 
    elseif conditions then 
        elseif-part
    else
        else-part 
    end ;
    
(while)
    while  condition do 
        statements; 
    end ; 

(repeat-until)
    repeat 
        statements; 
    until  conditions;

(数值for 循环)
    for  var=exp1,exp2,exp3  do 
         loop-part 
    end 

(范型for 循环)
-- print all values of array 'a'  
    for  i,v  in ipairs(a) do print(v)  end  
-- print all keys of table 't' 
    for  k  in pairs(t)  do print(k)  end

范型for 和数值for 有两点相同: 
1. 控制变量是局部变量 
2. 不要修改控制变量的值

array = { "one", "Two", "Three" }
table = { ["+"] = "add", ["-"] = "sub" }

print ("array len : "..#array, "table len : "..#table)    -- # is table length op
for i, v in ipairs(array) do print(v) end
for k in pairs(table) do print(k..' is '..table[k]) end

>lua -e "io.stdout:setvbuf 'no'" "test.lua" 
array len : 3    table len : 0
one
Two
Three
+ is add
- is sub
>Exit code: 0

 

转载于:https://www.cnblogs.com/mark-huang/archive/2013/05/02/3055522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值