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.

Concept lesson, about 75 minutes, 10 steps

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

1What 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
Figure 1.1
Roblox Studio
Beacon Yard during Play, seen from above: six glowing yellow coin pads in a ring around the yard.

Select a numbered pin, or a row below, to read what it marks.

Figure 1.2.

The six coin pads collected into a single list.

CoinPads holds Pad1 to Pad6 and nothing else. After coinPads() runs, what is #pads?

Answer

6. Six parts pass the IsA check and table.insert adds each one at the end, so the list has 6 entries and # reports 6.

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

2When # 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 (or table.insert(list, 1, value) inserts at the front and shifts the rest up).
  • table.remove(list, i) removes index i and shifts later items down so no hole is left.
  • table.find(list, value) returns the first matching index, or nil.
Luau
local holed = {}
holed[1] = "Pad1"
holed[3] = "Pad3"
print(#holed)
 
local fine = { "Pad1", "Pad2", "Pad3" }
table.remove(fine, 2)
print(#fine, fine[2], table.find(fine, "Pad3"))
Figure 2.1. Expected output: 1 2 Pad3 2

This removes a collected pad from the list of pads that still have coins. Later, #ready is wrong. Which line causes it?

local ready = {"Pad1", "Pad2", "Pad3", "Pad4"}
local index = table.find(ready, "Pad2")
ready[index] = nil
print(#ready)
Answer

Line 3: ready[index] = nil. Fixed: table.remove(ready, index). Setting ready[2] to nil leaves a hole, so # is no longer reliable. table.remove takes the item out and closes the gap.

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

3Generalized 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 keys 1, 2, 3, ... in order and stops at the first nil hole.
  • pairs(t) visits every non-nil key (numbers, strings or objects), in no promised order.
  • for k, v in t do visits the array part in order and then any remaining keys, without extra function calls.
Luau
local holed = { [1] = "Pad1", [3] = "Pad3" }
 
local iCount = 0
for _index, _name in ipairs(holed) do
	iCount += 1
end
 
local pCount = 0
for _key, _name in pairs(holed) do
	pCount += 1
end
 
print("ipairs saw:", iCount)
print("pairs saw:", pCount)
Figure 3.1. Expected output: ipairs saw: 1 pairs saw: 2

Ways to loop over a table

OptionWhat it isWhen pros pick itTrade-offs
for k, v in t doLuau'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, #tCounts 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)
  1. 1
  2. 2
  3. 3
  4. An error
Answer

1. items[2] is nil, so ipairs visits index 1 ("Speed") and stops immediately before reaching index 3.

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

4A 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.

Server sideA debounce is an elevator button that ignores mashing.
In the pictureIn Roblox
Pressing the button ten timesTouched firing many times
The elevator comes onceOne payout
The button resets after the tripThe respawned coin has a fresh seen table

See the whole analogy cast

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
Figure 4.1
Luau
local seen = {}
local paid = 0
local touches = { "Ava", "Ava", "Ben", "Ava", "Ben" }
for _, player in touches do
	if seen[player] then
		continue
	end
	seen[player] = true
	paid += 5
end
print(paid, seen.Ava, seen.Cleo)
Figure 4.2. Expected output: 10 true nil

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

5Where 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?

  1. Pad2 refuses to pay, because the shared set already marks the player as seen
  2. Pad2 pays twice
  3. Nothing changes; each pad still has its own set
  4. The script errors because a table cannot be shared
Answer

Pad2 refuses to pay, because the shared set already marks the player as seen. There would be one set for the whole service. The player is already in it after Pad1, so every other pad, and every respawned coin, would skip them. Making the table inside spawnCoin gives each coin its own set.

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

6Copying 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.

Luau
local profile = { coins = 0, owned = { "Wrench" } }
local same = profile
same.coins = 25
print(profile.coins)
 
local copy = table.clone(profile)
copy.coins = 99
table.insert(copy.owned, "Speed")
print(profile.coins, #profile.owned)
Figure 6.1. Expected output: 25 25 2

What does this print?

local a = { coins = 5 }
local b = a
local c = table.clone(a)
b.coins = 10
print(a.coins, c.coins)
  1. 10 5
  2. 5 5
  3. 10 10
  4. 5 10
Answer

10 5. b and a are one table, so a.coins becomes 10. c is a shallow copy made while coins was still 5, so it keeps 5.

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

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

Luau
local items = {
	{ name = "Shield", price = 40 },
	{ name = "Speed", price = 25 },
	{ name = "CoinPack", price = 0 },
}
table.sort(items, function(a, b)
	return a.price < b.price
end)
for _, item in items do
	print(item.name, item.price)
end
local names = {}
for _, item in items do
	table.insert(names, item.name)
end
print(table.concat(names, ", "))
Figure 7.1. Expected output: CoinPack 0 Speed 25 Shield 40 CoinPack, Speed, Shield

Match each Beacon Yard expression to the kind of table it reads.

  1. Config.COIN_VALUE
  2. pads[1]
  3. seen[player]
  4. profiles[player].coins
Answer

Config.COIN_VALUE: A dictionary keyed by name; pads[1]: A sequence, first item; seen[player]: A set keyed by Player; profiles[player].coins: A nested table inside a dictionary. Config is a dictionary, pads is a 1-based sequence, seen is a set keyed by Player, and profiles maps each Player to their own profile table.

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

8Build it: count the pads at boot

Build along

m03-coins-count

  • src/server/init.server.luau
  1. Check out m03-coins-count (git checkout m03-coins-count) with rojo serve connected.

    You should see Studio syncs m03-coins-count with Config.luau, CoinService.luau and DataService.luau in place.

  2. In src/server/init.server.luau, on the line after CoinService.start(coinPads()), add print("[pads]", #coinPads()). Save and press Play.

    You should see Output shows [pads] 6 on the server when you press Play.

  3. Walk onto a pad and stay there. Watch the Coins counter 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.

  4. Stop and remove your print with git checkout -- src/server/init.server.luau.

    You should see git status shows a clean working tree.

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

9Challenges

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

Hints

  1. Build each name with "Pad" .. index.
  2. table.insert keeps the list free of holes.
Solution
luau
local names = {}
for index = 1, 6 do
	table.insert(names, "Pad" .. index)
end
print(#names, names[1], names[6])

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 in the lesson view; 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

Hints

  1. Start with totals[name] = (totals[name] or 0) + value inside for _, name in pickups do.
  2. A missing key reads as nil, so (totals[name] or 0) safely starts at 0.
Solution
luau
local function tally(pickups, value)
	local totals = {}
	for _, name in pickups do
		totals[name] = (totals[name] or 0) + value
	end
	return totals
end
Luau
-- pickups is a list of player names, one entry per coin collected.
-- Return a dictionary: name -> coins, where every pickup is worth value.
local function tally(pickups, value)
	local totals = {}
	return totals
end
Figure 9.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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 run game.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

Hints

  1. The test reads Config.PAD_COUNT, then looks for Pad1 to Pad6 under Workspace.Yard.CoinPads.
  2. MapBuilder does not require Config yet. Add local Config = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("Config")) :: { PAD_COUNT: number } near the top, then replace the 6 in for index = 1, 6 do.
  3. Keep table.insert, so the list stays free of holes.

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

10Recap

Recap

  1. # 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.
  2. 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.
  3. 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.

Next ModuleScripts and require

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