循环

2021-01-04  本文已影响0人  爱折腾的傻小子

循环

lua

while

while(confition)
do
  statements
end
while
-- while 循环
aa11 = 10
while( aa11 >= 1 )
do
    print(aa11)
    aa11 = aa11 - 1
end
--[[
10
9
8
7
6
5
4
3
2
1
]]

for

# var从exp1变化到exp2,每次变化以exp3为步长递增var,并执行一次"执行体"。exp3是可选的,如果不指定,默认为1
for var=exp1,exp2,exp3 do
  <循环体>
end
for i = 10, 1, -1 do
    print(i)
end
--[[
10
9
8
7
6
5
4
3
2
1
]]

for i = 5, 10 do
    print(i)
end
--[[
5
6
7
8
9
10
]]

function nn(x)
    print("开始执行")
    return x*2
end
for i = 1, nn(5), 2 do
    print(i)
end

--[[
开始执行
1
3
5
7
9
]]
for i, v in ipairs(a) 
do
  print(v)
end
#!/usr/local/bin/lua
days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}
for i, v in ipairs(days) do
    print(i .. " : " .. v)
end
--[[
1 : Sunday
2 : Monday
3 : Tuesday
4 : Wednesday
5 : Thursday
6 : Friday
7 : Saturday
]]
local tabFiles1 = {
    [1] = "t1",
    [4] = "t4",
    [9] = "t9",
    [7] = "t7"
}
-- 索引中断停止遍历 只输出 t1
for i, v in ipairs(tabFiles1) do
    print(i .. " : " .. v)
end
--[[
1 : t1
]]

for i, v in pairs(tabFiles1) do
    print(i .. " : " .. v)
end
--[[
4 : t4
1 : t1
9 : t9
7 : t7
]]

-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
local tabFiles2 = {
    [2] = "t2",
    [6] = "t6",
    [4] = "t4"
}
-- 什么都不会打印,因为ipairs采用升序遍历,当i=1时,v=nil,此时便停止遍历
for i, v in ipairs(tabFiles2) do
    print(i .. " : " .. v)
end

for i, v in pairs(tabFiles2) do
    print(i .. " : " .. v)
end
--[[
4 : t4
2 : t2
6 : t6
]]

-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
tabFiles3 = {
    "a",
    "b",
    [3] = "c",
    ["two"] = "yes"
}
-- 输出前三个参数,第四个key不是整数
for i, v in ipairs(tabFiles3) do
    print(i .. " : " .. v)
end
--[[
1 : a
2 : b
3 : c
]]

for i, v in pairs(tabFiles3) do
    print(i .. " : " .. v)
end
--[[
1 : a
2 : b
two : yes
3 : c
]]

Lua repeat...until

repeat
  statements
until( condition )
repeat
ii = 10
-- 注意 until 条件为true才会退出循环
repeat
    print("ii的值:" .. ii)
    ii = ii - 1
    print(ii <= 1)
until( ii <= 1 )
--[[
ii的值:10
false
ii的值:9
false
ii的值:8
false
ii的值:7
false
ii的值:6
false
ii的值:5
false
ii的值:4
false
ii的值:3
false
ii的值:2
true
]]

控制循环语句

break
a12 = 10
while (a12 < 20)
do
    print("a12的值:", a12)
    a12 = a12 + 1
    if a12 > 15 then
        break   -- 终止循环
    end
end
--[[
a12的值:  10
a12的值:  11
a12的值:  12
a12的值:  13
a12的值:  14
a12的值:  15
]]

无限循环

while( true )
do
   print("循环将永远执行下去")
end
上一篇下一篇

猜你喜欢

热点阅读