Lua中有两种for循环:
语法如下:
for var=exp1,exp2,exp3 do
statements
end
for将exp3作为exp1到exp2的步长,其中exp3可以忽略,默认步长是1
。
for i=1,f(x) do -- f(x)只会执行一次
print(i)
end
for i=10,1,-1 do
print(i)
end
local found = nil
for i=1,10 do
if i == 9 then
found = i
break
end
end
print(found) --> 9
break
语句。语法如下:
for i,v in ipairs(t) do -- 遍历数组
statements
end
for k,v in pairs(t) do -- 遍历table
statements
end
实例:
days = {"Suanday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
for i,v in ipairs(days) do
print(i, v)
end
--[[执行结果如下:
1 Suanday
2 Monday
3 Tuesday
4 Wednesday
5 Thursday
6 Friday
7 Saturday
]]
a = {a=1, b=2}
for k,v in pairs(a) do
print(k, v)
end
--[[执行结果如下:
b 2
a 1
]]