Table of Contents
Why Loops Matter
When you code games, you often need to repeat actions. Maybe you want to give a coin to every player, check all parts in a folder, or run some logic every frame. Writing the same line again and again is slow and hard to change later. Loops let you tell Lua, “Repeat this code for me,” while you only write it once.
In Roblox Lua, the two basic loop types you will meet first are for loops and while loops. They both repeat code, but they are used in different situations and look different.
A loop is any code structure that repeats the same block of instructions multiple times, as long as some condition is met.
In this chapter, you will focus on how for and while loops are written in Lua, what they are best used for, and how to avoid common mistakes like infinite loops.
Numeric `for` Loops
A numeric for loop repeats a block of code a specific number of times. It has a counter variable that starts at a value, moves toward an end value, and changes by a step each time.
The general form is:
for counter = start, finish, step do
-- code that uses counter
end
The step part is optional. If you leave it out, Lua uses 1 as the default step.
For example, to print the numbers from 1 to 5:
for i = 1, 5 do
print(i)
end
Here, i starts at 1, then becomes 2, then 3, 4, and 5. When i would next become 6, which is beyond the finish value, the loop stops.
You can also count backwards by using a negative step:
for countdown = 5, 1, -1 do
print(countdown)
end
This time, countdown starts at 5 and goes down by 1 until it reaches 1. When it would become 0, the loop stops.
Rule: In a numeric for loop, the loop runs while the counter has not passed the finish value, moving by the step each time. If the step is positive, it stops when the counter is greater than the finish. If the step is negative, it stops when the counter is less than the finish.
A numeric for loop is ideal when you know exactly how many times you want your code to run. For example, placing a certain number of parts in a line, repeating an effect ten times, or giving a bonus for each level up from 1 to 50.
Using Numeric `for` in Simple Roblox Situations
Even without going into Roblox specific scripting details, you can see how numeric for loops will be useful in games.
Imagine you want to create 10 platforms in a row. You might use something like:
for i = 1, 10 do
local part = Instance.new("Part")
part.Size = Vector3.new(4, 1, 4)
part.Position = Vector3.new(i * 6, 5, 0)
part.Parent = workspace
end
The important part for this chapter is how i controls the changing position. You do not place each platform by hand; the loop repeats your code and only i changes each time.
You can also combine numeric loops with conditions. For example, printing only even numbers between 1 and 10:
for i = 1, 10 do
if i % 2 == 0 then
print("Even number:", i)
end
endOr, use the step directly to skip values:
for i = 2, 10, 2 do
print("Even number:", i)
endIterating Over Collections With `for`
Lua also has a version of for that walks through items in a collection like a table. This is called a generic for loop. It uses iterators such as pairs and ipairs. You will learn tables in detail in another chapter, but you can see how loops can connect with them.
A simple example with numbered keys:
local scores = {10, 20, 30}
for index, value in ipairs(scores) do
print("Index:", index, "Score:", value)
endThere is an index, which is the position in the table, and a value, which is the data at that position. Each time the loop runs, it moves to the next item and stops when there are no more.
With non numbered keys:
local stats = {
Health = 100,
Coins = 50
}
for key, value in pairs(stats) do
print(key, value)
end
The main point for this chapter is that for loops are not only for counting numbers. They can also step through collections, which is very useful in game code when dealing with lists of players, items, or parts.
`while` Loops
A while loop keeps running as long as a condition is true. Unlike a numeric for loop, you do not tell it how many times to run. Instead, you tell it when to stop.
The basic form is:
while condition do
-- code to repeat
endLua checks the condition. If it is true, the loop block runs. After the block finishes once, Lua checks the condition again. If it is still true, it runs the block again. This continues until the condition becomes false.
For example, counting down with a while loop:
local count = 5
while count > 0 do
print(count)
count = count - 1
end
print("Done!")
The line count = count - 1 is very important. Without changing count, the condition count > 0 would never become false, and the loop would never stop.
Rule: A while loop must change something inside its block so that the condition will eventually become false. If not, you create an infinite loop that never ends.
Common `while` Loop Patterns in Games
You can use while loops for logic that should continue until some game state changes.
For example, a simple timer that counts seconds:
local timeLeft = 10
while timeLeft > 0 do
print("Time left:", timeLeft)
timeLeft = timeLeft - 1
wait(1)
end
print("Time is up!")
Here, wait(1) pauses for one second between each loop, so this countdown actually takes 10 seconds in game time. The loop naturally stops when timeLeft becomes 0.
You can also see how while can track a condition like a player's health or a game phase, and keep repeating logic until that condition changes.
Infinite Loops and How to Avoid Them
An infinite loop is a loop that never finishes. It can freeze your script or even your game. Infinite loops can happen with both for and while, but are more common with while because you control the condition and the updates yourself.
A simple example of a bad infinite loop:
local x = 0
while x < 5 do
print("Still looping")
-- Forgot to change x
end
Since x never changes, x < 5 is always true, so the loop never ends.
In Roblox, another problem is using loops that run very quickly with no pause. For example:
while true do
-- intense work with no wait
endThis can use a lot of CPU and cause your game to lag or stop responding.
To prevent these problems, always check that your while loop:
- Changes variables that affect the condition.
- Has a condition that can realistically become false.
- Uses
wait()or similar pauses when you are looping continuously over time.
Rule: Avoid while true do loops that have no clear stop condition and no wait() or delay. They can cause severe performance issues in your Roblox game.
`repeat` and `while` Comparison
Lua has another loop, repeat ... until, that is closely related to while. While this chapter focuses on for and while, it helps to understand the difference briefly, because you might see it in Roblox scripts.
A while loop checks the condition first, then runs the block:
while condition do
-- may not run at all if condition is false at the start
end
A repeat loop runs the block once, then checks the condition at the end:
repeat
-- always runs at least once
until condition
So the main difference is whether the code is guaranteed to run at least once. The mechanical detail here is just to show how while fits into the family of loops you will later use.
Choosing Between `for` and `while`
Both for and while can repeat code, but each is better in different situations.
Use a for loop when you know how many times you want to repeat something, or when you are walking through a known collection of items. Examples include counting from 1 to 100, creating 20 coins, or checking all players in a list.
Use a while loop when the number of repetitions is not fixed, and you want the loop to continue until some condition changes. Examples include running code until a timer reaches zero, until a player dies, or until a round of the game ends.
Thinking about your loop in this way will help you write clearer and safer code.
Breaking and Continuing Loops
Sometimes you want to stop a loop early before it finishes naturally. Lua provides the break statement to do this. There is also continue in some languages, but in Roblox Lua you achieve similar behavior with if statements and break.
To stop a loop early, you can write:
for i = 1, 10 do
if i == 5 then
break
end
print(i)
end
This loop prints 1, 2, 3, and 4. When i equals 5, the break stops the loop completely.
You can use break inside while loops too:
while true do
local value = math.random(1, 10)
print("Got:", value)
if value == 7 then
print("Stopping loop")
break
end
wait(0.1)
endThis loop keeps running until it randomly gets the value 7, then stops.
If you want to skip the rest of the loop body for a specific turn, you can use if to wrap the code you want to run conditionally. For example, printing only odd numbers in a loop:
for i = 1, 10 do
if i % 2 == 1 then
print("Odd:", i)
end
endHere you do not actually leave the loop early, but you decide when to run the code inside it based on a condition.
Loops and Basic Efficiency
Loops are a very powerful tool, but they can also slow down your game if they do too much work too often.
A few simple habits help keep your loops efficient:
Try to avoid heavy calculations or unnecessary work inside loops that run many times per second. For example, do not create new objects inside a loop that runs every frame unless you really need to.
Cache values that do not change, instead of recomputing them inside the loop. For example, store a reference to a part outside the loop, and use that reference inside.
Use wait() or other timing functions if a loop is meant to run over time. This leaves time for other parts of your game to run smoothly.
These habits will matter more as your games get larger, but it is good to start thinking about them as soon as you begin using loops.
Summary
In this chapter, you explored two main kinds of loops that you will use in Roblox Lua. The numeric for loop, which repeats code a fixed number of times or over a collection, and the while loop, which repeats as long as a condition is true. You saw how to count up and down, how to avoid infinite loops, and how to stop a loop early with break. Loops will appear in almost every script you write, and understanding their structure now will make more advanced Roblox game systems much easier to build later.