Loops

A loop is a way to repeat code multiple times. There are two types of loops: for and while.

For

A for loop repeats code when you want to iterate over a range, an array or a sequence of values.

for (local i = 1; i <= 3; i++) {
    print(i)
}
// Output:
// 1
// 2
// 3

As seen in above two examples, the for loop consists for 3 parts:

  • local i = 1, the iterator variable and its default value
  • i <= 5, the condition that determines when the for loop stops
  • i++, increments i with +1 after every loop

You can also loop through values in an array:

local items = ["sword", "shield", "potion"]
for (item in items) {
    print(item)
}

You can also use a range which allows for a shorter syntax:

// The 1..3 creates an array of [1, 2, 3]
for (i in 1..3) {
    print(i)
}

It’s also possible to get the index within the for loop You can also loop through values in an array:

local items = ["sword", "shield", "potion"]
for (index, value in items) {
    print("Index: " + index " has value " + value)
}
// Output:
// Index: 0 has value sword
// Index: 1 has value shield
// Index: 2 has value potion

While

A while loop will keep iterating until a condition becomes false.

local count = 1

while (count <= 3) {
    print(count)
    count++
}
// Output:
// 1
// 2
// 3

Repeat

A repeat loop will execute the code at least once, and until the condition is true.

local count = 1

repeat {
    print(count)
    count++
} until (count > 3)
// Output:
// 1
// 2
// 3

So the difference between a while and repeat loop:

  • while loop might never run if the while condition is false
  • repeat loop always runs at least once

Keyword: Break

Within any loop, you can use the break keyword. When break is reached, then the loop stops completely.

for (local i = 1; i <= 5; i++) {
    print(i)
    if (i == 3) break; // Stop the for loop once i is 3
}

local count = 1
while (count <= 5) {
    print(count)
    count++
    if (count == 3) break; // Stop the while loop early if the count is 3
}

local count = 1
repeat {
    print(count)
    count++
    if (count == 3) break; // Stop the repeat loop early if the count is 3
} until (count > 5)

// Output:
// 1
// 2
// 3

Keyword: Continue

Within any loop, you can also use the continue keyword. When continue is placed in a loop, it will skip to the next iteration.

for (local i = 1; i <= 5; i++) {
    if (i % 2 == 0) continue; // If i is an even number, then skip to the next loop iteration
    print(i)
}

local count = 1
while (count <= 5) {
    print(count)
    count++
    if (count % 2 == 0) continue;
}

local count = 1
repeat {
    print(count)
    count++
    if (count % 2 == 0) continue;
} until (count > 5)

// Output:
// 1
// 3
// 5

Categories:

Updated: