Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Luau Scripting

Control Flow: Decisions and Loops in Luau

Control the flow of Roblox scripts with if, elseif and else, numeric and generic for loops, while and repeat loops, break and continue, and safe loops with task.wait.

So far scripts ran straight through. Real games need to make decisions ("is the player alive?") and repeat work ("give every player a sword"). Control flow is the set of statements that choose and repeat. In Luau that means if, for, while and repeat.

if, elseif, else

LUA
local health = 35

if health <= 0 then
	print("Game over")
elseif health < 50 then
	print("Low health!")
else
	print("Healthy")
end

Every if ends with end, and the condition is followed by then. Parentheses around the condition are optional. Luau checks the branches top to bottom and runs the first one that is true.

Remember that only nil and false count as false. This is why a common test for "does this exist?" is:

LUA
local coin = workspace:FindFirstChild("Coin")
if coin then
	coin:Destroy()
end

Combine conditions with and, or and not:

LUA
if player.Team == "Red" and not player.IsDead then
	print("Red player is ready")
end

if as an expression

When you only need a value, an if expression is shorter:

LUA
local label = if health > 0 then "alive" else "knocked out"

Numeric for loop

Use it to repeat a known number of times:

LUA
for i = 1, 5 do
	print("Round", i)
end

The loop variable i is a fresh local each time. The range includes both ends. A third value sets the step, which may be negative:

LUA
for i = 10, 0, -2 do
	print(i)      --> 10 8 6 4 2 0
end

Do not change i inside the loop; it is the loop's own counter.

Generic for loop

The generic for walks a collection. Use ipairs for arrays (in order, with index) and pairs for dictionaries (unordered):

LUA
local fruits = {"apple", "banana", "cherry"}

for index, fruit in ipairs(fruits) do
	print(index, fruit)
end

local scores = {Ana = 12, Ben = 7}
for name, score in pairs(scores) do
	print(name, score)
end

Luau also lets you loop over a table directly, without calling ipairs or pairs:

LUA
for _, child in workspace:GetChildren() do
	print(child.Name)
end

The underscore _ is the conventional name for a value you ignore. This pattern, looping over GetChildren(), is the one you will write most.

while and repeat

while checks the condition before each pass and may never run:

LUA
local fuel = 3
while fuel > 0 do
	print("Burning...", fuel)
	fuel -= 1
	task.wait(1)
end

repeat ... until checks after each pass, so it always runs at least once, and stops when the condition becomes true:

LUA
local tries = 0
repeat
	tries += 1
	print("Try", tries)
until tries >= 3

A game loop often uses while true do. This is fine only if the loop yields (pauses), because a loop that never yields freezes the server:

LUA
while true do
	print("tick")
	task.wait(1)        -- required!
end

A loop with no task.wait() and no end condition stalls the whole server until Roblox shows "script exhausted allowed execution time". Always check that every while true loop contains a wait.

break and continue

break leaves the loop; continue (supported in Luau) skips to the next pass:

LUA
for i = 1, 10 do
	if i % 2 == 0 then
		continue       -- skip even numbers
	end
	if i > 7 then
		break          -- stop once past 7
	end
	print(i)           --> 1 3 5 7
end

Nested loops

A loop inside a loop creates a grid, perfect for building a wall of bricks:

LUA
for row = 1, 4 do
	for column = 1, 6 do
		local brick = Instance.new("Part")
		brick.Size = Vector3.new(4, 2, 2)
		brick.Position = Vector3.new(column * 4, row * 2, 0)
		brick.Anchored = true
		brick.Parent = workspace
	end
end

This builds 24 bricks. Loops like this are how scripts build levels, and later lessons use them for creating parts in code.

Stand-in: decisions

The runnable examples are JavaScript stand-ins of the same logic. First: a function that picks a message, with the first true branch winning.

JS Stand-in: if / elseif / else (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: loops and continue

JS Stand-in: for, continue and break (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that Luau's repeat ... until cond stops when the condition is true, so the JavaScript version uses while (!cond).

Choosing the right loop

Need Use
Repeat N times for i = 1, N do
Visit every item of an array for _, item in array do
Visit key and value of a dictionary for key, value in dict do
Repeat until something changes while condition do
Run once, then maybe again repeat ... until
Run forever as a game loop while true do ... task.wait() end

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does for i = 10, 0, -2 do count?

    The third value is the step. A negative step counts downward, and the end value is included.
  2. 2. What is essential inside while true do in a Roblox script?

    Without a yield the loop never lets the engine continue and the script is stopped.
  3. 3. When does repeat ... until stop?

    repeat runs the body, then stops once the until condition is true.
  4. 4. What does continue do?

    continue jumps to the next iteration of the loop.

Summary

  • if / elseif / else / end chooses the first true branch; if also works as an expression.
  • for i = a, b, step repeats a counted number of times; for _, v in collection visits items.
  • while tests first, repeat ... until tests last; every endless loop needs task.wait().
  • break leaves a loop and continue skips to the next pass.

Next: Functions, Events and Errors