PcoWSkbVqDnWTu_dm2ix

5 min

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

The 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.

for
count
control
variable
=
1
start
value
,
10
end
value
,
1
increment
value
do

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

The 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 do and end executes and the true/false condition is reevaluated afterward.

The while loop can also be used for infinite game loops by using simply true as the condition:

repeat

A repeat 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 true do loop, you can force it to end with the break command so the script can continue running the code following it:

Tags:
  • coding
  • lua
  • loop
  • repeat