lua-Loop(循环)

while

Syntax:

while(condition)
do
statement(s)
end

1
2
3
4
5
6
a = 10
while( a < 20 )
do
print("value of a:", a)
a = a+1
end

for

参考链接1

The for statement has two variants(变种): the numeric for and the generic for.

Numeric for (数值for循环)

官方文档

for var=exp1,exp2,exp3 do
something
end

  • exp1: initial condition
  • exp2: final condition
  • exp3: step
    • this exp is optional,when absent, Lua assumes one as the step value.
1
2
3
4
5
6
7
8
9
10
11
12
13
--[[
exp1: i = 10
exp2: 4
exp3: -2
]]
for i = 10, 4, -2 do
print(i) -- 10,8,6,4
end

-- Omit exp3
for i = 1, 3 do
print(i) -- 1,2,3
end

Generic for (泛型for循环)

官方文档

The generic for loop allows you to traverse(遍历) all values returned by an iterator function.

ipairs()

When the traversed value is nil, the for loop will terminate.

1
2
3
4
local a = {"one","two",nil,1,2,3.14}
for index, value in ipairs(a) do
print(value) -- one, two
end
pairs()

When the traversed value is nil, the for loop will omit the nil value and continue to the rest.

1
2
3
4
local a = {"one","two",nil,1,2,3.14}
for index, value in pairs(a) do
print(value) -- one, two, 1, 2, 3.14
end

repeat…until

Similiar to other programing language.

nested loop

Similiar to other programing language.


lua-Loop(循环)
https://jackiedai.github.io/2024/01/03/004lua/lua-Loop-循环/
Author
lingXiao
Posted on
January 3, 2024
Licensed under