• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
梦想照进灵魂
博客园    首页    新随笔    联系   管理    订阅  订阅
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

 

posted on 2013-05-02 22:08  梦想照进灵魂  阅读(260)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3