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
Step 1 of 9
Two 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?
Press 1 to 4 to choose, Enter to check.
Step 2 of 9
What 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
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.)
Step 3 of 9
String 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.
Ways 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))
Press 1 to 4 to choose, Enter to check.
Step 4 of 9
If 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.
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)
Press 1 to 4 to choose, Enter to check.
Step 5 of 9
Functions 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.
Why does trySpend check if price <= 0 then return false ... end before subtracting?
Press 1 to 4 to choose, Enter to check.
Step 6 of 9
Catching 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 ok, result = pcall(function() error("boom") end) runs. What are ok and result?
Press 1 to 4 to choose, Enter to check.
Step 7 of 9
Jar 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.
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?
Press 1 to 4 to choose, Enter to check.
Step 8 of 9
Challenges
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
Meet the criteria above, then record your own result. No test grades this check.
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; 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
Step 9 of 9
Recap
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