Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua for Loop

Lua for Loop

Lua loops 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.

In the Lua programming language, there are two main types of for statements::


Numeric for loop

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


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

var changes from exp1 to exp2, each time incrementing var by the step exp3, and executes once "execution 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 are not evaluated again. For example, the f(x) above is executed only once before the loop starts, and its result is used in the subsequent loop.

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

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.

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


--Print all values of array a
a = {"one", "two", "three"}
for i, v in ipairs(a) do
    print(i, v)
end 

i is the array index value, v is the array element value corresponding to the index. ipairs is an iterator function provided by Lua 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 loops Lua Loops