A loop lets you execute code multiple times. Each type of Lua loop repeats a block of code but in different ways.
for 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.
The following example loop starts at 1 and counts up until 5, printing the value of
count (the control variable) on each iteration:
If the optional increment value is included in the statement, a positive value will count up while a negative value will count down:
while 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.
while 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 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
while true do loop, you can force it to end with the
break command so the script can continue running the code following it: