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.

Lab lesson, about 30 minutes, 12 steps

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:

WriteMeans
a == ba equals b
a ~= ba does not equal b
a < b, a > bless than, greater than
a <= b, a >= bat most, at least
Luau
local coins = 30
local SHIELD_PRICE = 40
print(coins >= SHIELD_PRICE)
print(coins < SHIELD_PRICE)
print(coins ~= 30)
Figure 1.1. Expected output: false true false

What does this print?

local state = "Idle"
print(state ~= "Active")
  1. true
  2. false
  3. Idle
  4. nil
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.

Luau
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
Figure 2.1. Expected output: Not enough coins. You need 10 more

Change 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
  1. alive
  2. knocked out
  3. alive knocked out
  4. nothing
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,
Figure 3.1

elseif checks the next condition only if the ones before it were false.

Luau
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
Figure 3.2. Expected output: Drones incoming!

What does this print?

local coins = 100
if coins >= 25 then
	print("Speed")
elseif coins >= 40 then
	print("Shield")
end
  1. Speed
  2. Shield
  3. Speed Shield
  4. nothing
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 "".

Luau
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)
Figure 4.1. Expected output: 0 counts as true in Luau Ready false true
Go 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
  1. has coins
  2. broke
  3. 0
  4. nil
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:

Luau
local secondsLeft = 3
while secondsLeft > 0 do
	print("Round starts in", secondsLeft)
	secondsLeft -= 1
end
print("Go!")
Figure 5.1. Expected output: 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
  1. 3
  2. 4
  3. 5
  4. It never stops
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.

Luau
for pad = 1, 3 do
	print("Spawning coin on Pad" .. pad)
end
 
for health = 100, 0, -50 do
	print("Drone health:", health)
end
Figure 6.1. Expected output: Spawning coin on Pad1 Spawning coin on Pad2 Spawning coin on Pad3 Drone health: 100 Drone health: 50 Drone health: 0

What does this print?

local total = 0
for i = 1, 4 do
	total += i
end
print(total)
  1. 4
  2. 6
  3. 10
  4. 1234
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

Both sidesA function is a recipe card: give it ingredients, follow the steps, get a dish back.
In the pictureIn Roblox
The recipe nameThe function name
Blanks for the ingredientsParameters in the function definition
The dish handed across the counterThe value handed back by return

See the whole analogy cast

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

Luau
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)
Figure 7.1. Expected output: 5 25 20

award(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)))
  1. 6
  2. 9
  3. 12
  4. double(6)
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.

Luau
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)
Figure 8.1. Expected output: 8 a is nil and b is 8

In the cell above, why is a nil?

  1. showDouble crashed
  2. showDouble printed 8 but returned nothing, and nothing means nil
  3. print deletes values
  4. a was misspelt
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.

Luau
local function award(coins, pickups)
	return coins + pickups * 5
end
 
print(award(10, 2))
print(award(10))
Figure 9.1. Run it in the lesson view or in the Studio command bar.

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.

Luau
local total = 0
 
local function addCoins(amount)
	local bonus = 1
	total += amount + bonus
end
 
addCoins(5)
addCoins(5)
print(total)
print(bonus)
Figure 10.1. Expected output: 12 nil

total 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)
  1. 1
  2. 99
  3. nil
  4. an error
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

  1. Return the result of a comparison.
  2. Which comparison is true when the two numbers are equal?
Solution
luau
local function canAfford(coins, price)
	return coins >= price
end
Luau
local function canAfford(coins, price)
	-- return true if coins is at least price, otherwise false
end
Figure 11.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. if, elseif and else pick the first true branch; in Luau, only false and nil count as false (0 counts as true).
  2. while repeats while a condition holds, and numeric for counts from a start to an end including both.
  3. 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.

Next Programming from zero, part 3: tables and the coin counter

Open this step in lesson mode · Link to this step · This confused me