One of the beauty of programming is automation. In this chapter, we are going to learn the concept of Loops. This fundamental logic concept in Lua programming allow you to execute a block of code repeatedly based on a condition. In Lua, there are three main types of loops: while
, for
, and repeat...until
. Each type of loop serves different purposes. In this guide, I will walk you through each type of loop step-by-step. Examples will be provided to help you understand how to use them effectively.
You can use Lua Online Editor to try the loop examples below:
Lua while Loop
This is a commonly used looping condition. The definition of it is basically:
while
loop repeatedly executes a block of code as long as a given condition is true. It checks the condition before executing the loop’s body.
It is useful but you must pay attention to use it. Just imagine if you create a while condition without ending, you make a big trouble. We usually call it Infinite Loop (or endless loop). It literally mean the program will keep repeating itself forever, and never come to an end.
Basic syntax of while-loop
while condition do
-- Code to execute while the condition is true
end
Simple while loop example
local count = 1
while count <= 5 do
print("Count: " .. count)
count = count + 1
end
In this example, you can tell inside the the loop, it will keep printing the values once the count
value increment from 1 to 5. Intuitively, the loop stops when count
exceeds 5.
Now, let me show you how an infinite loop is created.
local condition = true
local count = 1
while condition do
print("Count: " .. count)
count = count + 1
end
You can tell the while condition will always be true. As the status of condition never change. As a result, the print statement will just keep doing it forever. If you run this script in the Lua compiler, the result will be an error.
RangeError [ERR_CHILD_PROCESS_STDIO_MAXBUFFER]: stdout maxBuffer length exceeded
Lua for
Loop
Alright, next we are gonna to talk about the Lua for loop. Similar to While Loop, for loop is used for iterating over a range of values. It is particularly useful when you know the number of iterations in advance. There are different types of for loop in Lua, let’s take a look of the numeric first.
Numeric for
Loop
Over a sequence of numbers, the numeric loop iterate itself until the reach the end. Let’s see the basic syntax:
for variable = start, stop, step do
-- Code to execute for each value in the range
end
Basically, we call the variable
the loop control variable. And then the start
is the initial value of the variable. Next is the stop
which is the final value of the variable. Finally step
is the increment (or decrement) value (optional, defaults to 1). Let’s walk through an example to understand how it’s work.
Lua for loop example
for i = 1, 5 do
print("Value: " .. i)
end
You should able to interpret the above program. The variable is i and the initial value is 1. And the stop sign is 5. So the program will print out:
Output:
Value: 1
Value: 2
Value: 3
Value: 4
Value: 5
Try it out in your own Lua compiler.
Generic for Loop
With the generic for
loop, you can iterate over all elements in a collection. For example, you can iterate with an array or a table. If you are not familiar with these data type, you can take a look of our related tutorials here. Let’s see the syntax of the generic for loop:
for key, value in pairs(collection) do
-- Code to execute for each key-value pair in the collection
end
Lua generic for loop example
local fruits = {"apple", "banana", "cherry"}
for index, fruit in ipairs(fruits) do
print("Fruit " .. index .. ": " .. fruit)
end
You can tell the loop iterates over the fruits array (Just imagine it’s like a storage box) and prints each fruit along with its index. Noted that in Lua, the first index of an array is 1. Unlike many other programming languages where array indices start from 0, Lua arrays (which are represented by tables) are 1-indexed. This means that when you access elements of an array, the first element is at position 1.
Lua repeat…until Loop
Quite similar to while loop, the repeat…until loop checks the condition after executing the loop’s body. Pay attention to the sequence, this means that the loop will always execute at least once. The syntax is shown below:
repeat
-- Code to execute
until condition
Lua repeat until example
local count = 15
repeat
print("Count: " .. count)
count = count + 1
until count > 30
You should able to simulate the program. The loop prints the values of count
from 15 to 30. The loop will stops when count
exceeds 30.
Can we combine different loop together?
The answer is surely YES. Nest loops inside one another can perform more complex logic iterations. But noted that you need to carefully handle the OPEN and the CLOSE of each loop, or otherwise you will make a chaos.
Lua Nested loop example
for i = 1, 3 do
print("Outer loop iteration: " .. i)
for j = 1, 2 do
print(" Inner loop iteration: " .. j)
end
end
We can the first for loop the outer loop. It runs three times, and for each iteration of the outer loop, the inner loop runs twice. This results in a total of 6 iterations.
Conclusion
We cover most of the basic knowledge of Lua loops. You need more practice in this chapter as I promise you will heavily use loop concept in your coming game development journey. In Lua, the while
, for
, and repeat...until
loops provide the flexibility to handle various iteration scenarios. By understanding and using these loops, you can write more efficient and effective Lua programs.