Roblox For Loops and While Loops in Luau: A Beginner Guide
Last updated:
Quick answer: Luau has four loops: a numeric for loop (for i = 1, 10 do) for counting, a generic for loop (for k, v in pairs(t) do) for tables and children, while loops that run as long as a condition is true, and repeat until loops that always run once. Every loop that can run for a long time needs a task.wait() inside it.
Loops in Luau repeat a block of code. Use a numeric for loop when you know how many times to repeat, a generic for loop to walk through a table or a list of children, and a while or repeat until loop when you repeat until some condition changes. In Roblox, any loop that runs for a while needs a task.wait() inside it, or the game freezes.
How does a numeric for loop work in Luau?
A numeric for loop counts from a start value to an end value. It is the right choice when you know the number of repetitions in advance:
for i = 1, 5 do
print("Count: " .. i)
end
-- prints Count: 1 through Count: 5
Both ends are included, so 1, 5 runs five times. A third number sets the step, which can be negative to count down:
for i = 10, 0, -2 do
print(i) -- 10, 8, 6, 4, 2, 0
end
A practical Roblox example is building a staircase out of parts. Put this in a Script in ServerScriptService:
for i = 1, 10 do
local step = Instance.new("Part")
step.Size = Vector3.new(8, 1, 4)
step.Position = Vector3.new(0, i * 1, i * 4)
step.Anchored = true
step.Parent = workspace
end
The loop variable i only exists inside the loop, and changing it inside the body does not change how many times the loop runs.
How do I loop through a table or the children of an object?
The generic for loop walks every entry in a collection. Since Luau lets you iterate a table directly, the shortest form is:
local fruits = { "apple", "pear", "plum" }
for index, fruit in fruits do
print(index, fruit)
end
For clarity, most Roblox code still wraps the table in ipairs (ordered arrays) or pairs (dictionaries, or any table where order does not matter). Here is a very common pattern, tinting every part inside a folder:
local folder = workspace:WaitForChild("Decorations")
for _, child in ipairs(folder:GetChildren()) do
if child:IsA("BasePart") then
child.Color = Color3.fromRGB(255, 170, 0)
end
end
GetChildren() returns a fresh array each call, so editing parts inside the loop is safe. The underscore is the usual name for a loop variable you do not need. Dictionaries need pairs:
local prices = { Sword = 100, Shield = 60, Potion = 15 }
for itemName, price in pairs(prices) do
print(`{itemName} costs {price} coins`)
end
Dictionary order is not guaranteed, so never rely on it. The exact difference is covered in pairs vs ipairs in Luau, and the table basics are in Luau tables, arrays and dictionaries.
How does a while loop work in Luau?
A while loop checks its condition before every pass and keeps going as long as it is true:
local timeLeft = 10
while timeLeft > 0 do
print("Time left: " .. timeLeft)
timeLeft -= 1
task.wait(1)
end
print("Time is up!")
If the condition is false the first time, the body never runs. The infinite version, while true do, is how you write a loop that lives as long as the server does, such as a day and night cycle:
local Lighting = game:GetService("Lighting")
while true do
Lighting.ClockTime = (Lighting.ClockTime + 0.1) % 24
task.wait(0.1)
end
Without that task.wait(0.1), the loop would never yield. The engine cannot run anything else, and Studio shows a script timeout error. Use task.wait, not the old wait(); the reasons are in task.wait vs wait(). Code placed after a while true do loop in the same script will never run, so put a second loop in its own thread with task.spawn (see task.spawn, defer and delay).
What is repeat until in Luau?
repeat ... until is a while loop that checks at the end, so the body always runs at least once. It stops when the condition becomes true:
local Players = game:GetService("Players")
repeat
task.wait(1)
print("Waiting for players, currently " .. #Players:GetPlayers())
until #Players:GetPlayers() >= 2
print("Enough players, starting the round")
Note the flipped logic: while continues while the condition is true, repeat continues until it is true. This pattern is handy for lobbies, which you can extend in the round system tutorial.
How do I stop a loop early or skip an iteration?
break exits the loop immediately. continue skips the rest of the current pass and moves to the next one:
local Players = game:GetService("Players")
for _, player in ipairs(Players:GetPlayers()) do
if player.Name == "Guest" then
continue -- skip this player
end
local leaderstats = player:FindFirstChild("leaderstats")
if leaderstats and leaderstats.Coins.Value >= 100 then
print(player.Name .. " is rich!")
break -- stop checking after the first rich player
end
end
continue is a Luau addition that is not in standard Lua, so older Lua tutorials will tell you to use goto or nested if blocks instead. In Luau, just use continue.
Common mistakes with Roblox loops
- No yield in a long loop. A
while true dowithouttask.wait()freezes the server or client. Every long-running loop needs a wait. - Using
while wait() do. It works but relies on the deprecatedwait. Writewhile true do ... task.wait() endinstead. - Putting two infinite loops in one script. The second one never starts. Use
task.spawn(function() ... end)for the first. - Using
ipairson a dictionary.ipairsstops at the first missing numeric index and returns nothing for string keys. Usepairs. - Deleting items from an array while looping forward. Indexes shift and you skip entries. Loop backwards with
for i = #list, 1, -1 do, or build a new table. - Expecting
ito persist after the loop. The loop variable is local to the loop. Store it in an outerlocalif you need it afterward. - Looping over
GetDescendants()every frame. It is expensive on big models. Cache the result once, or listen for events likeChildAddedinstead.
Practice loops in a real game
Loops show up everywhere: spawning obstacles, iterating over players for a scoreboard, countdown timers. A good exercise is to combine them. Loop through Players:GetPlayers() and add 1 to each player's coin value every 5 seconds, using the setup from the leaderstats tutorial. If you want the wider picture first, start with the Roblox Luau tutorial or Roblox scripting for beginners.
Frequently asked questions
What is the difference between a for loop and a while loop in Roblox?
A for loop is meant for a known number of repetitions or for walking through a collection, such as every part in a folder. A while loop repeats for as long as a condition stays true and is meant for open-ended work like timers, lobby waiting, or background systems. Both can be written with the other, but picking the right one makes the code easier to read.
Why does my while true do loop crash Roblox Studio?
The loop never yields, so the engine cannot run anything else and the script times out or Studio freezes. Add task.wait() inside the loop body. Even task.wait() with no argument yields for one frame, which is enough to keep the game responsive.
Does Luau have continue?
Yes. Luau supports continue in for, while, and repeat loops, which skips to the next iteration. Standard Lua 5.1 does not have it, so tutorials written for plain Lua use goto or nested if statements instead. In Roblox you can use continue directly.
Should I use pairs, ipairs, or loop directly over the table?
Luau allows for k, v in tbl do, and it works for both arrays and dictionaries. Use ipairs when you want to make clear that you expect an ordered array, and pairs for dictionaries. All three perform similarly in practice, so choose based on readability.
Understand loop structures in Luau, including numeric, while, generic pairs, and ipairs iterators.