Easy Tutorial
❮ Lua Arrays Lua Debug ❯

Lua Loops

In many situations, we need to perform repetitive tasks, so certain statements need to be executed repeatedly in a program.

A set of statements that are executed repeatedly is called a loop body. Whether the loop continues or not is determined by the loop's termination condition.

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

A loop statement consists of the loop body and the loop's termination condition.

Lua provides the following loop handling methods:

Loop Type Description
while Loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for Loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
repeat...until Repeats the loop until a specified condition becomes true.
Nested Loops You can use one or more loops inside any other while, for, or repeat...until loop.

Loop Control Statements

Loop control statements change execution from its normal sequence.

Lua supports the following loop control statements:

Control Statement Description
break Statement Terminates the loop or statement and transfers execution to the statement immediately following the loop or statement.
goto Statement Transfers control to a labeled statement.

Infinite Loop

If the condition in a loop body is always true, the loop will execute indefinitely. Here is an example using a while loop:

Example

while( true )
do
   print("This loop will run forever")
end
❮ Lua Arrays Lua Debug ❯