Lua - Nested Loops
Lua programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax - Nested for loop
The syntax for a nested for loop statement in Lua is as follows −
for init,max/min value, increment
do
for init,max/min value, increment
do
statement(s)
end
statement(s)
end
Example - Print Months and Days
The following program uses a nested for loop to print months and days mapping −
main.lua
months = {"Jan", "Feb", "Mar"}
days = {"Sun", "Mon", "Tue"}
for x=1, #months
do
for y=1, #days
do
print(months[x], days[y])
end
end
Output
When you build and run the above code, it produces the following result.
Jan Sun Jan Mon Jan Tue Feb Sun Feb Mon Feb Tue Mar Sun Mar Mon Mar Tue
Syntax - Nested while loop
The syntax for a nested while loop statement in Lua programming language is as follows −
while(condition)
do
while(condition)
do
statement(s)
end
statement(s)
end
Example - Print Prime Numbers
The following program uses a nested while loop to get prime numbers−
main.lua
i = 2
while i < 25
do
j = 2
while j <= (i/j)
do
if(i%j == 0)
then
break
end
j = j + 1
end
if(j > (i/j))
then
print(i, " is prime")
end
i = i + 1
end
Output
When you build and run the above code, it produces the following result.
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime
Syntax - Nested repeat...until loop
The syntax for a nested repeat...until loop statement in Lua programming language is as follows −
repeat
statement(s)
repeat
statement(s)
until( condition )
until( condition )
Example - Get Prime Numbers
The following program uses a nested repeated until loop to get prime numbers−
main.lua
i = 2
repeat
do
j = 2
repeat
do
if(i%j == 0)
then
break
end
j = j + 1
end
until j > (i/j)
if(j > (i/j))
then
print(i, " is prime")
end
i = i + 1
end
until i > 25
Output
When you build and run the above code, it produces the following result.
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.