Lesson 1 of 6

Luau basics, part 1: Luau-specific text, decisions and pcall

Build on Programming from zero with what is Luau-specific for Roblox: a server-and-client bridge, string methods and the colon, string.format, if expressions, repeat and continue, multiple returns, pcall and editor type labels.

Concept lesson, about 40 minutes, 9 steps

By the end you can

  • Explain why a Roblox game runs as two separate programs (server and client)
  • Use Luau's string methods with the colon, string.format, if expressions and multiple return values
  • Catch runtime errors with pcall and keep both return values
  • Explain why Luau type annotations are checked before Play, never at run time

Before this: Programming from zero, part 1: values and variables, Programming from zero, part 2: decisions, loops and functions, Programming from zero, part 3: tables and the coin counter

1Two programs: server and client

Before writing Roblox scripts in Luau, keep one picture in mind. Every Roblox experience runs as two separate programs at the same time: one server running on Roblox's machines, and one client running on each player's phone or computer.

Picture a sports arena. The server is the referee holding the only real scoreboard, deciding who gets coins and who takes damage. Each client is one player's screen and controller at home, showing a copy of the match and sending requests.

Think of it as The referee with the only real scoreboard

Server sideRemember: The server is the referee with the only real scoreboard.

Module 3 (Client and server: who owns what) unpacks how the two programs talk and stay safe. Throughout Module 2, that single idea is all you need whenever a lesson says "the server" or "each side".

In Beacon Yard, a player walks onto a coin pad. Which program owns the real coin balance?

  1. The server, because it holds the official scoreboard
  2. That player's client, because they pressed the movement keys
  3. Both sides share one variable in memory
  4. Neither; Studio stores it in the place file
Answer

The server, because it holds the official scoreboard. The server runs the authoritative rules and holds every player's real balance. Clients only display a copy.

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

2What you already know, and what Luau adds

You already learned the core of programming in Programming from zero, part 1: values and variables and Programming from zero, part 2: decisions, loops and functions: numbers, strings, booleans, nil, local variables, +=, .., backtick interpolation, == and ~=, if/elseif/else, truthiness (only false and nil are falsy), while and numeric for loops, functions, return vs print, and local scope. We will not repeat those here.

This part focuses on the Luau features Roblox code uses every day that go beyond those basics. Start with two quick additions for values and numbers123:

  • typeof(value) names Roblox's own types such as "Vector3" and "CFrame", whereas plain type(value) only knows Luau's built-in kinds (for example, type(Vector3.new(22, 0, 0)) returns "vector" while typeof returns "Vector3").
  • tonumber("12") converts text to a number (returning nil if it fails), tostring(5) goes the other way, and math.clamp(x, low, high) keeps a value inside a range. Because computers store decimals in binary, 0.1 + 0.2 == 0.3 is false, which is why game currencies like Beacon Yard's coins stay whole numbers.
local Config = {
	COIN_VALUE = 5,
	COIN_RESPAWN_SECONDS = 4,
}
 
return Config
Figure 2.1
Luau with roblox-lite (not Roblox)
local pos = Vector3.new(22, 0, 0)
print(type(pos), typeof(pos))
print(tonumber("12"), tonumber("lots"), math.clamp(15, 0, 10))
print(0.1 + 0.2 == 0.3)
Figure 2.2. Expected output: vector Vector3 12 nil 10 false

A target has 100 health and each hit removes 34. Using // and +, how many hits does it take to reach 0 or less? (Work out 100 // 34, then check what is left over.)

Answer

3 hits. Two hits leave 32 health, which is above 0, so a third hit is needed. 100 // 34 + 1 is 3.

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

3String formatting, string methods and the colon

You already know .. and backtick interpolation `Coins: {coins}`. For fixed number formats such as +5 or 1.6 s, Luau provides string.format: %d inserts a whole number, %.1f a number with one decimal place, and %s a string3.

Strings also expose functions from the string library directly through a colon: name:upper() is shorthand for string.upper(name). The colon passes the value on its left as the first argument. You will see that colon syntax everywhere in Roblox (part:Destroy(), name:sub(4)), and the objects lesson explains how it works for your own tables too.

  • #text is the length in bytes; text:sub(4) slices from character 4 to the end.
  • text:find("Pad") returns the start and end positions (or nil).
  • string.split(text, ",") splits text into a list; text:rep(3) repeats it.
Luau
print(string.format("+%d", 5), string.format("%.1f s", 1.6))
local name = "Pad12"
print(#name, name:upper(), name:sub(4))
print(tonumber(name:sub(4)) + 1)
local parts = string.split("Speed,Shield,CoinPack", ",")
print(parts[2], #parts)
Figure 3.1. Expected output: +5 1.6 s 5 PAD12 12 13 Shield 3

Ways to build a message

OptionWhat it isWhen pros pick itTrade-offs
Concatenation ..Joins values with two dots.Short joins, and code that must read like older Lua.Gets noisy with many pieces; easy to forget a space.
Interpolation {x}Backtick strings with values in braces.Most new Roblox code, for readable messages and logs.Luau-only; tools that expect plain Lua 5.1 cannot parse it.
string.formatPlaceholders such as %d, %.1f and %s.Fixed number formats: +5, 1.6 s, padded columns. Beacon Yard uses it for coin feedback and countdowns.The placeholders are easy to mismatch with the arguments.

A coin pays 15. What does this string.format call print?

local amount = 15
print(string.format("+%d", amount))
  1. +15
  2. +%d15
  3. %d
  4. + 15
Answer

+15. string.format swaps %d for the whole number 15, so the text is +15.

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

4If expressions, guard clauses, repeat and continue

Sometimes you do not want to run a block of statements; you want to pick one of two values inside an expression. Luau adds an if expression for that: if condition then a else b4. Beacon Yard's CoinService uses one to read a coin's value and fall back to Config.COIN_VALUE if the value is not a number:

		local value = coin:GetAttribute("CoinValue")
		local amount = if typeof(value) == "number" then value else Config.COIN_VALUE
Figure 4.1

You may see the older Lua idiom x and a or b in tutorials. It breaks whenever a is false or nil, so prefer if x then a else b.

Two more control-flow habits show up across Roblox code:

  • Guard clauses: check invalid cases at the top of a function and return early so the real work stays unnested at the bottom.
  • Loop controls: repeat ... until condition runs at least once and stops when the condition becomes true; break exits a loop early; continue skips straight to the next iteration.
Luau
local function coinAmount(value)
	return if typeof(value) == "number" then value else 5
end
print(coinAmount(15), coinAmount("lots"), coinAmount(nil))
 
for pad = 1, 6 do
	if pad % 2 == 0 then
		continue
	end
	print("Odd pad", pad)
end
 
local coins = 0
repeat
	coins += 5
until coins >= 12
print(coins)
Figure 4.2. Expected output: 15 5 5 Odd pad 1 Odd pad 3 Odd pad 5 15

COIN_VALUE is 5 and a Speed upgrade costs 25. How many times does this repeat loop run?

local coins = 0
local pickups = 0
repeat
    coins += 5
    pickups += 1
until coins >= 25
print(pickups)
  1. 5
  2. 4
  3. 6
  4. 25
Answer

5. After 5 passes coins is 25, and 25 >= 25 is true, so the loop stops.

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

5Functions with multiple returns

A Luau function can return several values at once: return ok, remaining, message. Callers capture them with comma-separated names: local ok, remaining, message = trySpend(30, 25). Extra values you do not name are dropped, and any extra names on the left become nil.

Write local function for helpers that stay private inside one file. In the next lessons you will attach public functions to a module table instead.

Luau
local function trySpend(coins, price)
	if price <= 0 then
		return false, coins, "Bad price"
	end
	if coins < price then
		return false, coins, "Not enough coins"
	end
	return true, coins - price, "Bought"
end
print(trySpend(30, 25))
print(trySpend(0, 25))
local ok = trySpend(40, 40)
print(ok)
Figure 5.1. Expected output: true 5 Bought false 0 Not enough coins true

Why does trySpend check if price <= 0 then return false ... end before subtracting?

  1. A zero or negative price would let a buy succeed for free, or even add coins
  2. Luau cannot compare negative numbers
  3. It makes the function faster
  4. 0 is falsy in Luau, so the check is needed for if to work
Answer

A zero or negative price would let a buy succeed for free, or even add coins. Subtracting a negative price adds coins. Guarding price <= 0 prevents any caller from turning a purchase into a free gift.

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

6Catching errors with pcall

error("message") stops the current function with an error. Later in the course you will also call Roblox APIs that can throw errors at run time (for instance, network or storage calls). To keep going when a call throws, wrap it in pcallpcallCalls a function and catches any error, returning ok plus the result or the error text.Think of it as a safety net under a trapeze act: the show goes on if the act falls. ("protected call")3.

pcall always returns two or more values:

  • If the function succeeded: true, followed by whatever the function returned.
  • If the function threw an error: false, followed by the error text.

Keep both values. Writing local ok = pcall(work) throws the error message away, leaving you blind when something fails.

Figure 6.1.

Studio's command bar runs pcall around an error. The script keeps going and Output shows false plus the message.

Transcript
  1. 0:00 pcall runs the function and catches the error.
  2. 0:03 ok is false. The second value is the error text, not a thrown exception in the command bar.
Luau
local function doublePrice(price)
	if price <= 0 then
		error("price must be positive")
	end
	return price * 2
end
 
local ok, result = pcall(doublePrice, -5)
print(ok, result)
local fine, value = pcall(doublePrice, 5)
print(fine, value)
Figure 6.2. Expected output: false main:3: price must be positive true 10

local ok, result = pcall(function() error("boom") end) runs. What are ok and result?

  1. ok is false, and result is the error text containing "boom"
  2. ok is nil, and result is false
  3. The whole script crashes before ok is assigned
  4. ok is true, and result is "boom"
Answer

ok is false, and result is the error text containing "boom". pcall catches the error so execution continues, returning false as the first value and the error message as the second.

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

7Jar labels: editor checks vs run time

You may have noticed labels like : number or : BasePart in Beacon Yard's files. Those are type annotationsType annotationA label such as : number after a name, telling the type checker what a value should be.Think of it as a label on a jar.: hints read by the editor before you press Play5. The final lesson of this module teaches the type system in full; here is the one rule to remember early.

Both sidesType annotations is labels on jars.
In the pictureIn Roblox
The jarA variable, parameter or table field
What is insideThe value it holds at run time
The labelThe annotation, such as : number or : ShopItem
Reading the labels before cookingThe type checker running in the editor or in CI

See the whole analogy cast

Think of values as jars. The kind is what sits inside: coins, text, a yes or no. A type annotation such as local amount: number = 5 is a label stuck on the outside of the jar so the editor can warn you before the game runs.

Think of it as Labels on jars

The editor reads those labels before Play, never while the game is running. Run the cell below: a variable labelled number ends up holding text, and Luau runs it without complaining.

Both sidesRemember: Type annotations is labels on jars.

Luau
local price: number = 25
local sneaky: any = "twenty-five"
price = sneaky
print(price, type(price))
Figure 7.1. Expected output: twenty-five string
Where does it break?“Labels on jars” is a good picture of type annotations. Where does it stop being true?

It breaks here. Labels are checked before the game runs, and only then. While it runs, nothing reads them, so a value that arrives from a client or a DataStore can be anything whatever its label says.

The true model. Annotations feed a static checker that runs on the source code. At run time Luau ignores them. Code that receives outside data marks it unknown and narrows it with typeof, comparisons or type guards before treating it as a specific type.

A function takes amount: number, and while the game is running someone passes "lots" into it. Does the : number label stop the call at run time?

  1. No; type annotations are checked before running and ignored at run time, so code must check typeof(amount) == "number" if untrusted data can arrive
  2. Yes; Luau refuses the call with a type error before entering the function
  3. Yes, as long as the file starts with --!strict
  4. Only when called inside pcall
Answer

No; type annotations are checked before running and ignored at run time, so code must check typeof(amount) == "number" if untrusted data can arrive. Type annotations are static checks only. At run time Luau ignores them, which is why CoinService checks typeof(value) == "number" before paying.

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

8Challenges

Level 1, Apprentice

Challenge

Write a countdown formatter with string.format, math.ceil and math.max, and test it with 8, 7.2 and -3.

Start from
Any Run cell in this lesson

Done means

  • A function formatClock(seconds) returns text such as Next drill in 8s
  • It rounds up: 7.2 seconds shows as 8s
  • It never shows a negative number: -3 shows as 0s

Hints

  1. math.ceil rounds up and math.max(0, x) keeps a number from going below 0.
  2. string.format with %d puts a whole number into the text.
Solution
luau
local function formatClock(seconds)
	return string.format("Next drill in %ds", math.max(0, math.ceil(seconds)))
end
print(formatClock(7.2)) -- Next drill in 8s
print(formatClock(-3)) -- Next drill in 0s

Level 2, Builder

Challenge

Write safeAmount(value, fallback) in the cell below using an if expression and typeof. Passing the tests completes this challenge.

Start from
The Run cell below
Check it here
Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.

Done means

  • safeAmount returns value when it is a positive number
  • Text, nil, zero and negative numbers return fallback
  • All five assertions pass

Hints

  1. Use typeof(value) == "number" and value > 0 inside an if expression.
  2. return if typeof(value) == "number" and value > 0 then value else fallback
Solution
luau
local function safeAmount(value, fallback)
	return if typeof(value) == "number" and value > 0 then value else fallback
end
Luau
-- Return the coin amount to pay. Use value when it is a positive number.
-- Otherwise return the fallback. Never return a negative or non-number.
local function safeAmount(value, fallback)
	return value
end
Figure 8.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

9Recap

Recap

  1. A Roblox game runs as two separate programs: the server (referee and official scoreboard) and each player's client (screen and controller).
  2. Building on pre-programming, Luau adds typeof for Roblox types, colon string methods (name:upper()), string.format, if expressions, repeat/continue and multiple return values.
  3. pcall catches errors and returns ok plus the result or error text; keep both. Type annotations are checked by the editor before running, never at run time.

The server is the referee with the only real scoreboard, until the server is also the field itself, and it cannot see things that exist only on a client, such as a player's GUI or a LocalScript's effects.

Type annotations is labels on jars, until labels are checked before the game runs, and only then. While it runs, nothing reads them, so a value that arrives from a client or a DataStore can be anything whatever its label says.

Next Luau basics, part 2: Luau tables, holes, sets and copying

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