Lua for Loop

Lua 循环Lua Loops

In the Lua programming language, the for loop statement can repeatedly execute specified statements, and the number of repetitions can be controlled in the for statement.

The for statement in the Lua programming language has two major categories:

  • Numeric for loop
  • Generic for loop

Numeric for loop

The syntax format of the numeric for loop in the Lua programming language is:

for var=exp1,exp2,exp3 do  
    <执行体>  
end  

var changes from exp1 to exp2, incrementing var by exp3 on each change, and executes once"loop body"exp3 is optional; if not specified, it defaults to 1.

Example

Example

for i=1,f(x) do
    print(i)
end
 
for i=10,1,-1 do
    print(i)
end

The three expressions of for are evaluated once before the loop starts, and will not be evaluated again later. For example, f(x) above is executed only once before the loop starts, and its result is used in the subsequent loops.

Verification is as follows:

Example

#!/usr/local/bin/lua  
function f(x)  
    print("function")  
    return x*2  
end  
for i=1,f(5) do print(i)  
end

The output of the above example is:

function
1
2
3
4
5
6
7
8
9
10

It can be seen that the function f(x) is executed only once before the loop starts.


Generic for loop

The generic for loop traverses all values through an iterator function, similar to the foreach statement in Java.

The syntax format of the generic for loop in the Lua programming language is:

--打印数组a的所有值  
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end 

i is the array index value, and v is the array element value corresponding to the index. ipairs is an iterator function provided by Lua, used to iterate over arrays.

Example

Loop through the array days:

Example

#!/usr/local/bin/lua  
days = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}  
for i,v in ipairs(days) do  print(v) end  

The output of the above example is:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Lua 循环Lua Loops

Other extensions