Lesson 1 of 6
Luau basics, part 2: Luau tables, holes, sets and copying
Build on pre-programming part 3 with Luau-specific table skills: holes and #, ipairs vs pairs vs generalized iteration, sets keyed by Player, table.clone shallow copies, table.sort and Beacon Yard's coin pads.
By the end you can
- Predict what
- Choose between generalized for-in, ipairs, pairs and numeric for loops
- Use a table keyed by any value as a set, and copy tables with table.clone while watching for nested references
- Sort lists of records in place with table.sort and join strings with table.concat
Before this: Luau basics, part 1: Luau-specific text, decisions and pcall, Programming from zero, part 3: tables and the coin counter
Step 1 of 10
What you know, and what Luau's table library adds
You already met 1-based lists, dictionaries, nested tables, for k, v in t do, and shared table references in Programming from zero, part 3: tables and the coin counter. This part goes straight to the Luau-specific table traps and tools that matter in real Roblox scripts: holes and #, ipairs vs pairs, sets keyed by instances, table.clone, and table.sort.
At m03-coins-count, Beacon Yard's server gathers all six coin pads into one list using table.insert and hands it to CoinService:
local function coinPads(): { BasePart }
local folder = workspace:WaitForChild("Yard"):WaitForChild("CoinPads")
local pads: { BasePart } = {}
for _, child in folder:GetChildren() do
if child:IsA("BasePart") then
table.insert(pads, child)
end
end
return pads

Select a numbered pin, or a row below, to read what it marks.
The six coin pads collected into a single list.
CoinPads holds Pad1 to Pad6 and nothing else. After coinPads() runs, what is #pads?
Step 2 of 10
When # lies: holes, insert, remove and find
#list returns a border: an index n where list[n] is not nil and list[n + 1] is nil1. A list with consecutive keys 1..n and no gaps is a sequence, and it has exactly one border, the count, so # is reliable on it. If you clear an item in the middle with list[2] = nil, you leave a hole. Now there can be several borders, #list may return any of them, and it is no longer guaranteed to be the count you expect. Only ipairs reliably stops at the first nil.
Use the table library so lists stay sequences2:
table.insert(list, value)appends at the end (ortable.insert(list, 1, value)inserts at the front and shifts the rest up).table.remove(list, i)removes indexiand shifts later items down so no hole is left.table.find(list, value)returns the first matching index, ornil.
This removes a collected pad from the list of pads that still have coins. Later, #ready is wrong. Which line causes it?
Press 1 to 4 to choose, Enter to check.
Step 3 of 10
Generalized iteration vs ipairs and pairs
In modern Luau you usually write for k, v in t do (generalized iteration). Older Roblox code and tutorials often wrap the table in ipairs(t) or pairs(t), and knowing the difference saves bugs:
ipairs(t)visits integer keys1, 2, 3, ...in order and stops at the firstnilhole.pairs(t)visits every non-nil key (numbers, strings or objects), in no promised order.for k, v in t dovisits the array part in order and then any remaining keys, without extra function calls.
Ways to loop over a table
| Option | What it is | When pros pick it | Trade-offs |
|---|---|---|---|
| for k, v in t do | Luau's generalized iteration. | New Roblox code; Beacon Yard uses it everywhere. | Luau-only. Lists go in order; dictionary keys have no promised order. |
| ipairs(t) | Visits 1, 2, 3 and stops at the first nil. | Older code, and code that must also run on plain Lua. | Stops silently at a hole. |
| pairs(t) | Visits every key in any order. | Older code for dictionaries and sets. | Same result as generalized iteration, with more words. |
| Numeric for i = 1, #t | Counts indexes yourself. | When you need index math, such as walking backwards while removing items. | Trusts #, so a hole breaks it. |
What does this print?
local items = { "Speed", "Shield", "CoinPack" }
items[2] = nil
local count = 0
for _, v in ipairs(items) do
count += 1
end
print(count)
Press 1 to 4 to choose, Enter to check.
Step 4 of 10
A table as a set: who already touched this coin
In Luau, any non-nil value can be a table key, including a Roblox Player instance. A table whose values are all true works as a set: seen[player] = true marks the player as present, and seen[player] reads nil for everyone else, in instant lookup time without scanning a list.
CoinService at m03-coins-count keeps a seen set on each coin. Because a player's feet and legs can bump a coin many times in one step, the set plus a claimed flag act as a debounce so one visit pays once.
| In the picture | In Roblox |
|---|---|
| Pressing the button ten times | Touched firing many times |
| The elevator comes once | One payout |
| The button resets after the trip | The respawned coin has a fresh seen table |
Pressing an elevator button ten times brings the elevator once. The coin's claimed flag and seen set do the same for a stream of touches.
Think of it as An elevator button that ignores mashing
local claimed = false
local seen: { [Player]: boolean } = {}
coin.Touched:Connect(function(hit: BasePart)
if claimed then
return
end
local player = playerFromHit(hit)
if not player then
return
end
if seen[player] then
return
end
seen[player] = true
claimed = true
Step 5 of 10
Where the elevator picture breaks
Server sideRemember: A debounce is an elevator button that ignores mashing.
An elevator button is one shared switch. Beacon Yard's guard is not one switch: seen is a table with one entry per player, and it is created inside spawnCoin, so every coin gets a fresh one.
Where does it break?“An elevator button that ignores mashing” is a good picture of a debounce. Where does it stop being true?
It breaks here. One button serves everyone, but a game debounce must be kept per player and on the server, or one player blocks another and an exploiter skips it.
The true model. A debounce is state the server keeps, usually per player, that says an action already happened. Checks that decide whether the action is legal run before that state is written.
Suppose local seen = {} moved out of spawnCoin, to the top of CoinService, so all six pads share one set. A player collects from Pad1, then walks to Pad2. What happens?
Press 1 to 4 to choose, Enter to check.
Step 6 of 10
Copying safely with table.clone
From Programming from zero, part 3: tables and the coin counter, you know local same = profile shares the same table. When you really need a second, independent table, call table.clone(t)2.
Watch the one catch: table.clone is a shallow copy. It copies top-level fields (coins), but any nested table inside (owned) is still shared between the original and the clone.
What does this print?
local a = { coins = 5 }
local b = a
local c = table.clone(a)
b.coins = 10
print(a.coins, c.coins)
Press 1 to 4 to choose, Enter to check.
Step 7 of 10
Sorting and joining: table.sort and table.concat
table.sort(list, compare) sorts a sequence in place. Pass a function compare(a, b) that returns true when a must come strictly before b (return false when they are equal!). Once a list of strings is in the order you want, table.concat(names, ", ") joins them faster and cleaner than looping with ...
Match each Beacon Yard expression to the kind of table it reads.
Step 8 of 10
Build it: count the pads at boot
Build along
src/server/init.server.luau
Check out
m03-coins-count(git checkout m03-coins-count) withrojo serveconnected.You should see Studio syncs m03-coins-count with Config.luau, CoinService.luau and DataService.luau in place.
In
src/server/init.server.luau, on the line afterCoinService.start(coinPads()), addprint("[pads]", #coinPads()). Save and press Play.You should see Output shows [pads] 6 on the server when you press Play.
Walk onto a pad and stay there. Watch the
Coinscounter in the player list.You should see Collecting from one pad pays 5 once, even while you keep standing on it, and a new coin appears there about 4 seconds later.
Stop and remove your print with
git checkout -- src/server/init.server.luau.You should see git status shows a clean working tree.
Step 9 of 10
Challenges
Level 1, Apprentice
Challenge
Build the list of pad names without any parts, using table.insert so #names is exact.
- Start from
- Any Run cell in this lesson
Done means
- A loop from 1 to 6 builds the list Pad1 to Pad6 with table.insert
- #names prints 6 and names[1] prints Pad1
- Nothing is stored at index 0
Meet the criteria above, then record your own result. No test grades this check.
Level 2, Builder
Challenge
Write tally(pickups, value) in the cell below. Passing the assertions 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
- tally returns a dictionary mapping each player name to their total coins
- Players who collected more than once accumulate their total
- An empty pickup list returns an empty table
Level 3, Professional
Challenge
Switch to m06-drone-wrench (where MapBuilder and challenges/luau-basics.luau live), move the pad count into Config, and drive MapBuilder's loop from it. The written solution is in the game repo at challenges/solutions/luau-basics.md.
- Start from
- The game at milestone m06 (download)
- Grade it
- To grade work from an earlier milestone, apply your challenge changes to a checkout based on
m14-ship, which includes the Course Runner. In Studio, press Play, then rungame.ServerScriptService.RunGameTests:Invoke("luau-basics")in the server command bar. Copy the pass code from Output.
Done means
- Config.luau has PAD_COUNT = 6
- Self-check, the test cannot see it: MapBuilder requires Config and its pad loop runs from 1 to Config.PAD_COUNT
- The yard still has Pad1 to Pad6 and no Pad0
- The Course Runner prints TEST PASS luau_basics_pad_count and a pass code
Step 10 of 10
Recap
Recap
- # counts a sequence up to its first hole, and ipairs stops at the first nil. Add with table.insert and remove with table.remove so lists never grow holes.
- Use generalized for k, v in t do in new Luau code; pairs visits every non-nil key in any order, and tables keyed by Player work as fast sets.
- table.clone makes a one-level (shallow) copy, table.sort sorts sequences in place with a strict compare function, and table.concat joins lists of strings.
A debounce is an elevator button that ignores mashing, until one button serves everyone, but a game debounce must be kept per player and on the server, or one player blocks another and an exploiter skips it.
Queued for review
- This removes a collected pad from the list of pads that still have coins. Later, #ready is wrong. Which line causes it?
- What does this print?
- Suppose local seen = {} moved out of spawnCoin, to the top of CoinService, so all six pads share one set. A player collects from Pad1, then walks to Pad2. What happens?
- What does this print?
- Match each Beacon Yard expression to the kind of table it reads.