Lua learning (10)--Lua for loop

There are two types of for statements in the Lua programming language:

  1. Numeric for loop
  2. Generic for loop

Numeric for loop

Numerical for loop syntax format in Lua programming language:

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

var changes from exp1 to exp2, incrementing var by exp3 for each change, and executing the "executive body" once. exp3 is optional and defaults to 1 if not specified.

Example

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

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

function f(x)  
    print("function ",x) 
    return x*2   
end  
for i=1,f(5) do 
    print(i)  
end  

Output result:

function 5
1
2
3
4
5
6
7
8
9
10

You can see that the function f(x) is executed only once before the loop starts.

Generic for loop

The generic for loop iterates over all values ​​through an iterator function, similar to the foreach statement in java.
Generic for loop syntax format in Lua programming language:

--打印数组a的所有值  
for i,v in ipairs(a) 
    do print(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 to iterate over arrays.

Example
Loop array days:

days = {"Suanday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}  
for i,v in ipairs(days) do  
    print(v) 
end   

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325575486&siteId=291194637