Loops
Loops
A loop lets you execute code multiple times. Each type of Lua loop repeats a block of code but in different ways.
Loop Types
for — do
The for
—do
loop lets you run a command or group of commands a set number of times. The basic syntax includes a control variable, a start value, an end value, and an optional increment value.
for
count

variable
=
1

,
10

,
1

do
Beginning with the start value, the loop will count up or down each time it runs the code between do
and end
until it reaches the end value. For example, the following loop starts at 1 and counts up until 5, printing the value of count
(the control variable) on each iteration:
If an increment is included in the statement, a positive value will count up while a negative value will count down:
while — do
The while
—do
loop evaluates if a condition is true or false. If false, the loop ends and the code following it continues to execute. If true, the code between do
and end
executes and the true/false condition is reevaluated afterward.
The while
—do
loop can also be used for infinite game loops by using simply true
as the condition:
wait()
inside an infinite loop, as omitting it can freeze the game.
repeat — until
A repeat
—until
loop repeats until a certain condition is met. Note that the code between repeat
and until
is executed at least once because the conditional test is performed afterward.
Breaking Loops
If you’re running a loop that won’t typically end, such as an infinite while
—do
loop, you can force it to end with the break
command so the script can continue running the code following it: