English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In many cases, we need to perform regular repeated operations, so certain statements need to be executed repeatedly in the program.
A group of statements that are repeatedly executed is called a loop body. Whether to continue repeating is determined by the termination condition of the loop.
A loop structure is a flow structure that repeatedly executes a certain section of the program under certain conditions. The program that is repeatedly executed is called the loop body.
A loop statement consists of two parts: the loop body and the termination condition of the loop.
Lua language provides the following types of loop processing methods:
Loop Type | Description |
---|---|
while Loop | Execute certain statements repeatedly when the condition is true. The condition is checked before executing the statement. |
for Loop | Repeat the specified statement, and the number of repetitions can be controlled in the for statement. |
repeat...until | Repeat the loop until the specified condition is true. |
Nested Loops | You can nest one or more loop statements within a loop (while do ... end; for ... do ... end; repeat ... until;). |
Loop control statements are used to control the flow of the program to achieve various program structures.
Lua supports the following loop control statements:
Control Statements | Description |
---|---|
break Statement | Exit the current loop or statement and start executing the next statement in the script. |
goto Statement | Transfer the control point of the program to a label. |
If the condition in the loop body is always true, the loop statement will keep executing forever. The following is an example using the while loop:
while(true) do print("The loop will keep executing forever") end