Lua Loops

In many cases, we need to perform certain regular repetitive operations, so in the program we need to repeatedly execute certain statements.

A group of repeatedly executed statements is called the loop body, and whether it can continue to repeat is determined by the loop termination condition.

A loop structure is a flow structure that repeatedly executes a certain segment of a program under certain conditions. The program that is repeatedly executed is called the loop body.

A loop statement is composed of two parts: the loop body and the loop termination condition.

The Lua language provides the following loop processing methods:

Loop TypeDescription
while loopWhen the condition is true, the program repeatedly executes certain statements. It checks whether the condition is true before executing the statements.
for loopRepeatedly executes specified statements, and the number of repetitions can be controlled in the for statement.
repeat...until Repeatedly executes the loop until the specified condition becomes true
Nested LoopsYou can nest one or more loop statements within a loop (while do ... end; for ... do ... end; repeat ... until;)

Loop Control Statements

Loop control statements are used to control the flow of the program to implement various structural ways of the program.

Lua supports the following loop control statements:

Control StatementDescription
break statementExits the current loop or statement and starts executing the statement immediately following it.
goto statementTransfers the control point of the program to a label.

Infinite Loop

In the loop body, if the condition is always true, the loop statement will execute forever. The following uses a while loop as an example:

Example

while( true )
do
   print("The loop will execute forever")
end
Other Extensions