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

Lua Nested Loops

Lua Nested Loops

Lua loops Lua Loops

The Lua programming language allows loops to be embedded within loops. The following example demonstrates the application of Lua nested loops.

Syntax

In the Lua programming language, the for Nested loop syntax format:


for init,max/min value, increment
do
   for init,max/min value, increment
   do
      statements
   end
   statements
end

In the Lua programming language, the while Nested loop syntax format:


while(condition)
do
   while(condition)
   do
      statements
   end
   statements
end

In the Lua programming language, the repeat...until Nested loop syntax format:


repeat
   statements
   repeat
      statements
   until( condition )
until( condition )

In addition to the above nesting of the same type of loops, we can also use different loop types for nesting, such as nesting a while loop inside a for loop body.

Example

The following example uses nested for loops:

Example

j

=

2

for

i

=

2

,

10

do

   

for

j

=

2

,

(

i

/

j

)

,

2

do

     

if

(

not

(

i

%

j

)

)

     

then

         

break

     

end

     

if

(

j

(

i

/

j

)

)

then

         

print

(

"the value of i is:"

,

i

)

     

end

   

end

end

The execution result of the code above is:


i 的值为:    8
i 的值为:    9
i 的值为:    10

Lua loops Lua Loops