A loop lets you execute code multiple times. Each type of Lua loop repeats a block of code but in different ways.
for — do
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.
Beginning with the start value, the loop will count up or down each time it runs the code between
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
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
end executes and the true/false condition is reevaluated afterward.
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
until loop repeats until a certain condition is met. Note that the code between
until is executed at least once because the conditional test is performed afterward.
If you’re running a loop that won’t typically end, such as an infinite
do loop, you can force it to end with the
break command so the script can continue running the code following it: