爱猫的狗

拥抱变化

导航

Lua - The Language 1 控制结构、table数据结构

1。用[[xxxxx]]直接引用字符串,类似于C#里的 @"xxxxx"。
   
比如:                       [[alo          [[
        "alo\n123\""    =   123"]]     =   alo
                                           123"]]

2。循环结构和选择结构
 
-- for and if
for i = 1,5 do
 print("i is now "..i)
    if i < 2 then
     print("small")
    elseif i < 4 then
     print("medium")
    else
     print("big")
    end
end

-- while
i=1
while i <=5 do
 print("i is now "..i)
    if i < 2 then
     print("small")
    elseif i < 4 then
     print("medium")
    else
     print("big")
    end
    i = i+1
end

-- repeat until,注意没有end
i=1
repeat
 print("i is now "..i)
    if i < 2 then
     print("small")
    elseif i < 4 then
     print("medium")
    else
     print("big")
    end
    i = i+1
until i == 6

输出结果:
i is now 1
small
i is now 2
medium
i is now 3
medium
i is now 4
big
i is now 5
big

3。简单的table结构

-- Arrays
myData = {}
myData[0] = "foo"
myData[1] = 42

-- Hash tables
myData["bar"] = "baz"

-- Iterate through the structure
for key,value in myData do
 print(key .. "=" .. value)
end

输出结果:
1=42
0=foo
bar=baz

4。嵌套的table结构

-- table结构
myPolygon = {
 color="blue",
 thickness=2,
 npoints=4;
 {x=0,y=0},
 {x=-10,y=0},
 {x=-5,y=4},
}

-- 索引形式
print(myPolygon["color"])

-- 点形式
print(myPolygon.thickness)

-- 三个子表,分别是myPolygon[1] 到 myPolygon[3]
print(myPolygon[2].x)
print(myPolygon[3]["y"])

输出结果:
blue
2
-10
4

posted on 2006-03-01 15:33  anf  阅读(246)  评论(0编辑  收藏  举报