2011年9月1日 星期四

[Lua] 筆記 to 28

-- Example 18   -- if elseif else statement

c=3
if c==1 then
    print("c is 1")
elseif c==2 then
    print("c is 2")
else
    print("c isn't 1 or 2, c is "..tostring(c))
end


-- Example 19   -- Conditional assignment.
-- value = test and x or y

a=1
b=(a==1) and "one" or "not one"
print(b)

-- is equivalent to
a=1
if a==1 then
    b = "one"
else
    b = "not one"
end
print(b)


-------- Output ------

one
one


-------- Output ------

c isn't 1 or 2, c is 3



-- Example 20   -- while statement.

a=1
while a~=5 do -- Lua uses ~= to mean not equal
    a=a+1
    io.write(a.." ")
end


-------- Output ------

2 3 4 5
Press 'Enter' key for next example


-- Example 20   -- while statement.

a=1
while a~=5 do -- Lua uses ~= to mean not equal
    a=a+1
    io.write(a.." ")
end


-------- Output ------

2 3 4 5


-- Example 22   -- for statement.
-- Numeric iteration form.

-- Count from 1 to 4 by 1.
for a=1,4 do io.write(a) end

print()

-- Count from 1 to 6 by 3.
for a=1,6,3 do io.write(a) end


-------- Output ------

1234
14


-- Example 23   -- More for statement.
-- Sequential iteration form.

for key,value in pairs({1,2,3,4}) do print(key, value) end


-------- Output ------

1       1
2       2
3       3
4       4


-- Example 24   -- Printing tables.
-- Simple way to print tables.

a={1,2,3,4,"five","elephant", "mouse"}

for i,v in pairs(a) do print(i,v) end


-------- Output ------

1       1
2       2
3       3
4       4
5       five
6       elephant
7       mouse




沒有留言:

張貼留言