Lua Loops
In many cases we need to perform some regular repetitive operations, so we need to repeatedly execute certain statements in a program.
A group of statements that are repeatedly executed is called a loop body. Whether repetition continues is determined by the loop's termination condition.
A loop structure is a flow structure that repeatedly executes a section of program under certain conditions. The repeatedly executed program is called the loop body.
A loop statement consists of two parts: the loop body and the loop termination condition.
The Lua language provides the following loop handling methods:
| Loop types | Description |
|---|---|
| while loop | When the condition is true, the program repeatedly executes certain statements. Before executing the statements, it first checks whether the condition is true. |
| for loop | Repeatedly execute specified statements; the number of repetitions can be controlled in the for statement. |
| repeat...until | Repeat the loop until the specified condition is true |
| Nested loops | One or more loop statements can be nested inside a loop (while do ... end; for ... do ... end; repeat ... until;) |
Loop control statements
Loop control statements are used to control the flow of a program to implement various structural forms of the program.
Lua supports the following loop control statements:
| Control statement | Description |
|---|---|
| break statement | Exit the current loop or statement and begin executing the statement immediately following the script. |
| goto statement | Transfer the program's control point to a label. |
Infinite loop
In a loop body, if the condition is always true, the loop statement will execute forever. The following takes the while loop as an example:
Example
while
(
true
)
do
(
"The loop will execute forever"
)
end