Lua Loops
Background
Luau, Roblox’s version of the programming language Lua, has a ton to offer when it comes to development. It’s a core element in game design that is needed to create a functioning experience.
A loop is something we can run to receive a certain result over a period of time. Luau offers three versions of loops that we can use. Each of them may look the same, however, they do not do the same!
In Luau, we have these loops:
while
for
repeat
Let’s dive into these loops!
While Loops
A while
loop is a loop that will always run as long it has a condition that is true
. If the condition is set to false
or nil
, it will not loop at all. Everything that comes after a while
, except false and nil, will always be seen as true.
The loop will always check that its condition is a true value before executing.
For example,
while true do
will returntrue
andwhile task.wait(1) do
will always returntrue
, butwhile false do
will not run.
A while
loop always includes a condition and a do
at last. We can use this syntax to create a new loop:
while { condition } do
statement(s)
end
Let’s test out a while
loop with the following code:
while true do
task.wait(1)
print("Hello world!")
end
Important
We always add atask.wait()
element to ourwhile
loop to ensure that the game doesn’t break due to the number of calls it sends. If you don’t include it, the loop will continue to run, which may result in an overload on the server.
As we can see, when we run our code, we will see in the console that it will print Hello World over and over again.
For Loops
A for
loop is a loop that allows us to execute something a specific amount of times. For example, we can use a for
loop to loop through a series of numbers or connected players in a server.
The syntax for creating a for
loop is the following:
for init,max/min value, increment do
statement(s)
end
A for loop lets us repeat something a specific amount of times. The init stands for initialization, and is where our result is located.
With the syntax, we can create a loop that counts down from 30 seconds. To do so, we’ll set the maximum (max) number to 30, the minimum (min) number to 1, and the increment to -1.
Let’s create a loop that counts down from 30:
for i = 30,1,-1 do
print(i)
end
Unlike the while
loop, we do not need to yield the loop. This is because our loop automatically stops after hitting our minimum number, and doesn’t repeat itself unless told so.
With the code in place, we’d get a result in the console which prints from 30 to 1.
We can also create a loop that loops through all the players in the PlayerService
. To do this, we use something called pairs
to loop through the player dictionary. You can read more about pairs and ipairs here.
To loop through the player dictionary, we’d normally do something like this:
for _, Player in pairs(game.Players:GetPlayers()) do
print(Player.Name) -- // This prints out the name of the players inside the dictionary!
end
This will print out the name of each player that is currently located inside of the dictionary. It’s common to use this loop in a :BindToClose()
function to save player data on player disconnects such as game shutdowns.
Repeat…until Loop
A repeat
loop is a loop that checks its condition at the bottom of the loop, unlike a while
loop, which checks it at the top.
It’s very similar to the while loop, but it’s not guaranteed to loop with its condition, unlike with the while loop.
The syntax for a repeat
loop is the following:
repeat
statement(s)
until { condition }
Notice something strange? That’s because the condition appears at the bottom of the loop rather than at the top! Therefore, the statements inside of this loop will run before the condition is tested.
If the condition of the loop is false
, the loop will run again and repeat this process until it returns a true
result.
This loop is somewhat uncommon to use, but you can still utilize it for a lot! For example, you can keep adding numbers to a set number, and once it reaches this number, it stops the loop. Like this:
local number = 20
repeat
number += 1 -- // Add 1 number to our variable "number"
print(number)
task.wait(1)
until number == 25 -- // If the value of our variable equals 25, then the loop stops.
Like with the
while
loop, we add atask.wait()
here to ensure the loop stops and doesn’t overload the server. In this scenario, it might’ve been a little unnecessary, but loops that handle bigger elements, like data saving, should have one.
We can also use a repeat until
loop for data saving! This is an example of a code where we save the data using a repeat until
loop:
local data = InstanceValue.Value
local success, result
repeat
success, result = pcall(function())
DataStore:UpdateAsync(Key, function()
return data
end)
end)
task.wait(1)
until success
if success then
print("Success!")
else
warn("Error! " .. tostring(result))
end
Notice that this is one of many ways to save data. A thumb rule is to find something that works for you, either as a one-time function or as a loop, like the one above.
Breaking
If you for some reason need to break a while
loop, you can add this to break the loop after a condition a met. For example, I like to add a break if a condition with an if
statement changes.
To implement a break
, you’d do this:
while true do
if Action == false then
-- // Repeat the loop
else
-- // Break the loop
break
end
end
The End
Created by Schedency, Founder @ Bluesync
Thank you for reading this tutorial, I hope you liked it! If you have a question regarding loops or just some general feedback, please, let me know down below!
Attributions:
- Syntax images from TutorialsPoint (External link)
Happy coding!