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 — do

The fordo 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
,
10
end
,
1
increment
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 whiledo 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 whiledo loop can also be used for infinite game loops by using simply true as the condition:

repeat — until

A repeatuntil 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 whiledo 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