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

Step 1 of 12

Comparisons

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
Ctrl Enter runs the cell. Checked against the expected output
Predict the output

What does this print?

local state = "Idle"
print(state ~= "Active")
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 2 of 12

Decisions 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
Ctrl Enter runs the cell. Checked against the expected output

Change coins to 50 and run it again.

Predict the output

What does this print?

local health = 0
if health > 0 then
	print("alive")
else
	print("knocked out")
end
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 3 of 12

More 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.

Luau
Ctrl Enter runs the cell. Checked against the expected output
Predict the output

What does this print?

local coins = 100
if coins >= 25 then
	print("Speed")
elseif coins >= 40 then
	print("Shield")
end
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 4 of 12

and, 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
Ctrl Enter runs the cell. Checked against the expected output
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 !=.

Predict the output

What does this print?

local coins = 0
if coins then
	print("has coins")
else
	print("broke")
end
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 5 of 12

Repeat 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
Ctrl Enter runs the cell. Checked against the expected output

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.

Predict the output

How many times does this print?

local coins = 0
while coins < 20 do
	coins += 5
	print(coins)
end
How many times does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 6 of 12

Count 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
Ctrl Enter runs the cell. Checked against the expected output
Predict the output

What does this print?

local total = 0
for i = 1, 4 do
	total += i
end
print(total)
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 7 of 12

Functions: 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
Ctrl Enter runs the cell. Checked against the expected output

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.

Predict the output

What does this print?

local function double(n)
	return n * 2
end
print(double(double(3)))
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 8 of 12

return 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
Ctrl Enter runs the cell. Checked against the expected output
Choose one

In the cell above, why is a nil?

In the cell above, why is a nil?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 9 of 12

When 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
Ctrl Enter runs the cell.

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.

Find the broken line

Fix the call so this prints 25.

Fix the call so this prints 25.

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 10 of 12

Where 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
Ctrl Enter runs the cell. Checked against the expected output

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.

Predict the output

What does this print?

local coins = 1
if true then
	local coins = 99
end
print(coins)
What does this print?

Press 1 to 4 to choose, Enter to check.

Link to this step · This confused me

Step 11 of 12

Challenge: 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; 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
Luau
Ctrl Enter runs the cell. Checked by tests

Link to this step · This confused me

Step 12 of 12

Recap

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

Link to this step · This confused me