Lesson 7 of 8
Programming from zero, part 2: decisions, loops and functions
Learn programming from zero in Luau, part 2 of 3: comparisons, if/elseif/else, truthiness, while and for loops, functions, return vs print, and scope.
By the end you can
- Compare values and choose paths with if, elseif, else, and, or and not.
- Repeat work with while and numeric for loops.
- Write functions with parameters, return values and local scope.
Before this: Programming from zero, part 1: values and variables
1Comparisons
Programs make decisions by comparing values. Each comparison answers true or false:
| Write | Means |
|---|---|
a == b | a equals b |
a ~= b | a does not equal b |
a < b, a > b | less than, greater than |
a <= b, a >= b | at most, at least |
local coins = 30
local SHIELD_PRICE = 40
print(coins >= SHIELD_PRICE)
print(coins < SHIELD_PRICE)
print(coins ~= 30)
false
true
falseWhat does this print?
local state = "Idle"
print(state ~= "Active")
Answer
true. ~= means 'not equal'. "Idle" is not "Active", so the answer is true.
Open this step in lesson mode · Link to this step · This confused me
2Decisions with if
An if statement runs some lines only when a condition is true. Its shape is always if condition then ... end, and else adds lines for when it is false. The lines inside are indented so you can see where they belong; Luau does not require it, but every reader does.
local coins = 30
local SHIELD_PRICE = 40
if coins >= SHIELD_PRICE then
coins -= SHIELD_PRICE
print("Shield bought. Coins left:", coins)
else
print("Not enough coins. You need", SHIELD_PRICE - coins, "more")
end
Not enough coins. You need 10 moreChange coins to 50 and run it again.
What does this print?
local health = 0
if health > 0 then
print("alive")
else
print("knocked out")
end
Answer
knocked out. 0 > 0 is false, so the else part runs. Exactly one of the two parts runs, never both.
Open this step in lesson mode · Link to this step · This confused me
3More than two choices: elseif
Beacon Yard's round is always in one of three states: Idle (waiting for someone to light the beacon), Active (drones are out) or Cooldown. The round and cooldown lengths come straight from Config.luau:
ROUND_SECONDS = 40,
COOLDOWN_SECONDS = 8,
elseif checks the next condition only if the ones before it were false.
local state = "Active"
if state == "Idle" then
print("Touch the beacon to start a round")
elseif state == "Active" then
print("Drones incoming!")
elseif state == "Cooldown" then
print("Next round soon")
else
print("Unknown state:", state)
end
Drones incoming!What does this print?
local coins = 100
if coins >= 25 then
print("Speed")
elseif coins >= 40 then
print("Shield")
end
Answer
Speed. The first true condition wins and the rest are skipped, even though 100 >= 40 is also true. Order your checks from most specific to least.
Open this step in lesson mode · Link to this step · This confused me
4and, or, not, and what counts as true
Combine conditions with and (both must be true), or (at least one) and not (flips it). In Luau, only false and nil count as false. Everything else counts as true, including 0 and the empty string "".
local coins = 0
local hasWrench = true
if coins then
print("0 counts as true in Luau")
end
if hasWrench and coins >= 0 then
print("Ready")
end
print(not hasWrench, not nil)
0 counts as true in Luau
Ready
false trueGo deeper If you know Python
In Python, 0, "", [] and None are all falsy. In Luau only false and nil are. if coins then is true even when coins is 0, so to test for zero write if coins == 0 then. Luau's nil is Python's None, and ~= is Python's !=.
What does this print?
local coins = 0
if coins then
print("has coins")
else
print("broke")
end
Answer
has coins. 0 is not false and not nil, so Luau treats it as true. Compare with == 0 when you mean zero.
Open this step in lesson mode · Link to this step · This confused me
5Repeat while something is true
Loops repeat code. A while loop checks its condition, runs its body, and checks again, until the condition is false. Here is the countdown before a round starts:
local secondsLeft = 3
while secondsLeft > 0 do
print("Round starts in", secondsLeft)
secondsLeft -= 1
end
print("Go!")
Round starts in 3
Round starts in 2
Round starts in 1
Go!If the body never makes the condition false, the loop runs forever. Delete the secondsLeft -= 1 line and run it: the runner stops it after a few seconds. In a real game, a loop like that freezes the server.
How many times does this print?
local coins = 0
while coins < 20 do
coins += 5
print(coins)
end
Answer
4. It prints 5, 10, 15 and 20. After 20 the check 20 < 20 is false, so the loop stops.
Open this step in lesson mode · Link to this step · This confused me
6Count with for
When you know how many times to repeat, a numeric for loop is simpler. for i = 1, 3 do runs with i as 1, then 2, then 3. A third number sets the step, and it can be negative.
for pad = 1, 3 do
print("Spawning coin on Pad" .. pad)
end
for health = 100, 0, -50 do
print("Drone health:", health)
end
Spawning coin on Pad1
Spawning coin on Pad2
Spawning coin on Pad3
Drone health: 100
Drone health: 50
Drone health: 0What does this print?
local total = 0
for i = 1, 4 do
total += i
end
print(total)
Answer
10. 1 + 2 + 3 + 4 = 10. The loop includes both ends, 1 and 4.
Open this step in lesson mode · Link to this step · This confused me
7Functions: name a job once, use it often
| In the picture | In Roblox |
|---|---|
| The recipe name | The function name |
| Blanks for the ingredients | Parameters in the function definition |
| The dish handed across the counter | The value handed back by return |
A functionFunctionA named piece of code you can run whenever you like.Think of it as a recipe card: give it ingredients, get a dish back. is a named piece of code you can run whenever you like. Think of it as a recipe card: you give it parametersParameterA named input of a function, filled in by the arguments of each call.Think of it as a blank on the recipe card that each cook fills in. (the blanks for the ingredients), it follows the steps, and it can return a result (the finished dish).
Think of it as A recipe card: give it ingredients, follow the steps, get a dish back
local COIN_VALUE = 5
local function award(coins, pickups)
return coins + pickups * COIN_VALUE
end
print(award(0, 1))
print(award(10, 3))
local after = award(award(0, 2), 2)
print(after)
5
25
20award(10, 3) is a call. Luau sticks the tag coins on 10 and pickups on 3, runs the body, and the call becomes the returned value. A call can be used anywhere a value can, even inside another call.
What does this print?
local function double(n)
return n * 2
end
print(double(double(3)))
Answer
12. The inner call runs first: double(3) is 6. Then double(6) is 12.
Open this step in lesson mode · Link to this step · This confused me
8return is not print
Beginners often mix these up. print shows a value to you and the program carries on. return hands a value back to whoever called the function, and the function stops right there. A function with no return hands back nil.
Both sidesRemember: A function is a recipe card: give it ingredients, follow the steps, get a dish back.
local function showDouble(n)
print(n * 2)
end
local function getDouble(n)
return n * 2
end
local a = showDouble(4)
local b = getDouble(4)
print("a is", a, "and b is", b)
8
a is nil and b is 8In the cell above, why is a nil?
Answer
showDouble printed 8 but returned nothing, and nothing means nil. Printing is not returning. A function hands back nil unless it says return.
Open this step in lesson mode · Link to this step · This confused me
9When an argument is missing
Call a function with fewer arguments than it has parameters, and Luau does not stop at the call to ask for the missing ingredient. It fills the blank with nil and keeps going. This error is so common that it is worth seeing on purpose:
Where does it break?“A recipe card: give it ingredients, follow the steps, get a dish back” is a good picture of a function. Where does it stop being true?
It breaks here. A human cook stops and asks when an ingredient is missing, but a Luau function runs anyway with nil in the missing parameter, and fails only later when code tries to use that nil.
The true model. A function call binds arguments to parameters in order; any omitted parameter receives nil, and any extra argument is ignored. A function without return hands back nil.
local function award(coins, pickups)
return coins + pickups * 5
end
print(award(10, 2))
print(award(10))
Read the error carefully. It points at line 2, inside award, but the mistake is on line 6, where the call left out an argument. An error often shows up some distance from its cause.
Fix the call so this prints 25.
local function award(coins, pickups)
return coins + pickups * 5
end
print(award(10))
Answer
Line 4: print(award(10)). Fixed: print(award(10, 3)). award needs both arguments. 10 + 3 * 5 = 25.
Open this step in lesson mode · Link to this step · This confused me
10Where a name is visible: scope
A local variable is visible from the line where it is made to the end of the block it is in. A variable made inside a function cannot be seen outside it, so each function keeps its own working notes to itself 1.
If you leave out local, the variable is global by default: every block in the same script can see it and change it. That is why you nearly always write local. It keeps a name inside the block that needs it, and Luau also reads locals faster than globals 1.
Both sidesRemember: A variable is a name tag stuck on a value.
local total = 0
local function addCoins(amount)
local bonus = 1
total += amount + bonus
end
addCoins(5)
addCoins(5)
print(total)
print(bonus)
12
niltotal was made outside the function, so the function can see and change it. bonus lives only inside addCoins, so outside it is an unknown name, which is nil.
What does this print?
local coins = 1
if true then
local coins = 99
end
print(coins)
Answer
1. The inner local coins is a new tag that only exists until end. The outer coins was never changed.
Open this step in lesson mode · Link to this step · This confused me
11Challenge: can I afford it?
You now know enough to write a small function from scratch. Write it in the box, then press Run: a hidden test calls your function with a few numbers and displays Passed. Every test passed. when every answer is right.
Level 1, Apprentice
Challenge
Write a function that says whether a player can buy something. The cell below runs a hidden test when you press Run.
- Start from
- The code cell below the challenge, which runs a hidden test when you press Run.
- Check it here
- Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.
Done means
- canAfford(40, 40) is true
- canAfford(39, 40) is false
- canAfford(0, 0) is true
- It returns a boolean, not nil
Hints
- Return the result of a comparison.
- Which comparison is true when the two numbers are equal?
Solution
local function canAfford(coins, price)
return coins >= price
end
local function canAfford(coins, price)
-- return true if coins is at least price, otherwise false
end
Open this step in lesson mode · Link to this step · This confused me
12Recap
Retiring the analogy
You no longer need “a recipe card: give it ingredients, follow the steps, get a dish back”. A function call binds arguments to parameters in order; any omitted parameter receives nil, and any extra argument is ignored. A function without return hands back nil.
Recap
- if, elseif and else pick the first true branch; in Luau, only false and nil count as false (0 counts as true).
- while repeats while a condition holds, and numeric for counts from a start to an end including both.
- Functions take parameters and return values, which is different from printing. Omitted arguments arrive as nil, and a local lives only inside its block.
A function is a recipe card: give it ingredients, follow the steps, get a dish back, until a human cook stops and asks when an ingredient is missing, but a Luau function runs anyway with nil in the missing parameter, and fails only later when code tries to use that nil.
A variable is a name tag stuck on a value, until two tags can be stuck on the same table, so changing the table through one tag shows through the other, because there is only one table.
Queued for review
Next Programming from zero, part 3: tables and the coin counter
Open this step in lesson mode · Link to this step · This confused me