Nested Loops in Lua
Lua programming language allows nesting of loops within loops. The following example demonstrates the application of nested loops in Lua.
Syntax
The syntax for nested for loops in Lua programming language is:
for init, max/min value, increment
do
for init, max/min value, increment
do
statements
end
statements
end
The syntax for nested while loops in Lua programming language is:
while(condition)
do
while(condition)
do
statements
end
statements
end
The syntax for nested repeat...until loops in Lua programming language is:
repeat
statements
repeat
statements
until(condition)
until(condition)
In addition to nesting loops of the same type, we can also nest different types of loops, such as a while loop inside a for loop.
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("Value of i is:", i)
end
end
end
The output of the above code is:
Value of i is: 8
Value of i is: 9
Value of i is: 10