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.
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?
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 plaintype(value)only knows Luau's built-in kinds (for example,type(Vector3.new(22, 0, 0))returns"vector"whiletypeofreturns"Vector3").tonumber("12")converts text to a number (returningnilif it fails),tostring(5)goes the other way, andmath.clamp(x, low, high)keeps a value inside a range. Because computers store decimals in binary,0.1 + 0.2 == 0.3isfalse, which is why game currencies like Beacon Yard's coins stay whole numbers.
local Config = {
COIN_VALUE = 5,
COIN_RESPAWN_SECONDS = 4,
}
return Config
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)
vector Vector3
12 nil 10
falseA 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.
#textis the length in bytes;text:sub(4)slices from character 4 to the end.text:find("Pad")returns the start and end positions (ornil).string.split(text, ",")splits text into a list;text:rep(3)repeats it.
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)
+5 1.6 s
5 PAD12 12
13
Shield 3Ways to build a message
| Option | What it is | When pros pick it | Trade-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.format | Placeholders 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))
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
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
returnearly so the real work stays unnested at the bottom. - Loop controls:
repeat ... until conditionruns at least once and stops when the condition becomes true;breakexits a loop early;continueskips straight to the next iteration.
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)
15 5 5
Odd pad 1
Odd pad 3
Odd pad 5
15COIN_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)
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.
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)
true 5 Bought
false 0 Not enough coins
trueWhy does trySpend check if price <= 0 then return false ... end before subtracting?
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.
Studio's command bar runs pcall around an error. The script keeps going and Output shows false plus the message.
Transcript
- 0:00 pcall runs the function and catches the error.
- 0:03 ok is false. The second value is the error text, not a thrown exception in the command bar.
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)
false main:3: price must be positive
true 10local ok, result = pcall(function() error("boom") end) runs. What are ok and result?
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.
| In the picture | In Roblox |
|---|---|
| The jar | A variable, parameter or table field |
| What is inside | The value it holds at run time |
| The label | The annotation, such as : number or : ShopItem |
| Reading the labels before cooking | The type checker running in the editor or in CI |
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.
local price: number = 25
local sneaky: any = "twenty-five"
price = sneaky
print(price, type(price))
twenty-five stringWhere 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?
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
- math.ceil rounds up and math.max(0, x) keeps a number from going below 0.
- string.format with %d puts a whole number into the text.
Solution
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
- Use typeof(value) == "number" and value > 0 inside an if expression.
- return if typeof(value) == "number" and value > 0 then value else fallback
Solution
local function safeAmount(value, fallback)
return if typeof(value) == "number" and value > 0 then value else fallback
end
-- 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
Open this step in lesson mode · Link to this step · This confused me
9Recap
Recap
- A Roblox game runs as two separate programs: the server (referee and official scoreboard) and each player's client (screen and controller).
- 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.
- 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.
Queued for review
- In Beacon Yard, a player walks onto a coin pad. Which program owns the real coin balance?
- A coin pays 15. What does this string.format call print?
- 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.)
- local ok, result = pcall(function() error("boom") end) runs. What are ok and result?
- 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?
Next Luau basics, part 2: Luau tables, holes, sets and copying
Open this step in lesson mode · Link to this step · This confused me