Lesson 7 of 8
Programming from zero, part 3: tables and the coin counter
Learn programming from zero in Luau, part 3 of 3: lists, dictionaries, nested tables, shared table references, string interpolation and a working coin counter.
By the end you can
- Store data in tables used as lists (numbered from 1) and as dictionaries (key to value).
- Explain why assigning a table shares the same table instead of copying it.
- Build a small coin counter that collects, spends and reports coins like Beacon Yard's.
Before this: Programming from zero, part 2: decisions, loops and functions
1Tables as lists
So far each variable holds one value. A tableTableLuau's one container: a set of key and value pairs that works as a list, a dictionary or an object.Think of it as a cabinet of labelled drawers. holds many. Written with curly braces and commas, it is a list: items in order, numbered from 1 1.
local pads = {"Pad1", "Pad2", "Pad3"}
print(pads[1], pads[3])
print(#pads)
table.insert(pads, "Pad4")
print(#pads, pads[4])
print(pads[10])
Pad1 Pad3
3
4 Pad4
nilpads[1] reads item 1. #pads is the length. table.insert adds to the end. Asking for an item that is not there gives nil, not an error.
What does this print?
local drones = {"Alpha", "Bravo"}
print(drones[0])
Answer
nil. Luau lists start at 1, so there is nothing at 0. If you know Python, this is the biggest habit to unlearn.
Open this step in lesson mode · Link to this step · This confused me
2Visit every item
To do something with each item, loop over the table. for index, item in pads do visits each item in order, with its position.
local pads = {"Pad1", "Pad2", "Pad3"}
for index, pad in pads do
print(index, pad)
end
local prices = {25, 40, 10}
local sum = 0
for _, price in prices do
sum += price
end
print("Total:", sum)
1 Pad1
2 Pad2
3 Pad3
Total: 75_ is a name for "a value I am not going to use". Older Roblox code writes in ipairs(pads) for lists, and you will see it everywhere; it gives the same result here.
Go deeper If you know Python
for index, pad in pads do is like Python's for index, pad in enumerate(pads, start=1):. Luau has no list slicing, and #pads plays the part of len(pads).
What does this print?
local hits = {10, 15, 15}
local health = 100
for _, damage in hits do
health -= damage
end
print(health)
Answer
60. 100 - 10 - 15 - 15 = 60. The loop subtracts each item in turn.
Open this step in lesson mode · Link to this step · This confused me
3Tables as dictionaries
A table can also map keys to values, like a price list. This is a dictionary. Read a value with table.key, or with table["key"] when the key is in a variable or has spaces. A missing key gives nil.
local prices = {
Speed = 25,
Shield = 40,
}
print(prices.Speed, prices["Shield"])
local item = "Shield"
print(item, "costs", prices[item])
prices.Magnet = 60
print(prices.Magnet, prices.Rocket)
25 40
Shield costs 40
60 nilThat is exactly the shape of Beacon Yard's real Config table, which every other script reads its numbers from:
local Config = {
ROUND_SECONDS = 40,
COOLDOWN_SECONDS = 8,
COIN_VALUE = 5,
COIN_RESPAWN_SECONDS = 4,
SURVIVAL_BONUS = 10,
DRONE_SPEED = 12,
DRONE_DAMAGE = 15,
DRONE_HIT_COOLDOWN = 1,
DRONE_MAX_HEALTH = 100,
WRENCH_DAMAGE = 34,
WRENCH_RANGE = 14,
STUN_SECONDS = 1.6,
WALK_SPEED = 16,
What does this print?
local Config = { COIN_VALUE = 5, WRENCH_RANGE = 14 }
local key = "WRENCH_RANGE"
print(Config[key] - Config.COIN_VALUE)
Answer
9. Config[key] looks up WRENCH_RANGE, which is 14. 14 - 5 = 9.
Open this step in lesson mode · Link to this step · This confused me
4Visit every key
Looping over a dictionary gives each key and its value. There is one catch: the order is not guaranteed. Never write code that depends on a dictionary's loop order.
local prices = { Speed = 25, Shield = 40 }
local total = 0
local count = 0
for name, price in prices do
total += price
count += 1
end
print(count, "items, total", total)
2 items, total 65This cell prints totals rather than each name, precisely because the names could come out in either order.
You loop over { Speed = 25, Shield = 40, Magnet = 60 } and print each name. Which is true?
Answer
The order is not guaranteed, so code must not depend on it. Dictionaries have no order. If you need one, put the names in a list and loop over that.
Open this step in lesson mode · Link to this step · This confused me
5Tables inside tables
Values in a table can be tables too. Beacon Yard keeps one small table per player, all inside a bigger table keyed by player name. Later this key becomes the player's user id.
local profiles = {}
profiles["Player1"] = { coins = 0, hasShield = false }
profiles["Player2"] = { coins = 30, hasShield = true }
profiles.Player1.coins += 5
print(profiles.Player1.coins, profiles.Player2.coins)
print(profiles.Player2.hasShield)
print(profiles.Player3)
5 30
true
nilThis crashes with: attempt to index nil with 'coins'. Fix it so Player3 starts with 0 coins and the program prints 5.
local profiles = {}
profiles.Player3.coins = 0
profiles.Player3.coins += 5
print(profiles.Player3.coins)
Answer
Line 2: profiles.Player3.coins = 0. Fixed: profiles.Player3 = { coins = 0 }. profiles.Player3 was nil, and you cannot set a field on nothing. Create Player3's table first.
Open this step in lesson mode · Link to this step · This confused me
7Building messages
Joining text with .. gets clumsy. Luau has string interpolationString interpolationA backtick string with values in braces, such as `Coins: {coins}`.Think of it as a form with blanks that fill themselves in.: write the text between backticks, and anything in curly braces is worked out and inserted 2.
local name = "Player1"
local coins = 45
print(`{name} has {coins} coins`)
print(`Shield in {40 - coins} coins`)
print(`Can buy shield: {coins >= 40}`)
Player1 has 45 coins
Shield in -5 coins
Can buy shield: trueThe second line has a bug: you cannot need minus five coins. In the project below you will use math.max(0, 40 - coins), which picks the larger of two numbers, to stop at zero.
What does this print?
local pad = 3
print(`Pad{pad} has {pad * 5} coins`)
Answer
Pad3 has 15 coins. Inside backticks, each {...} is replaced by its value. Nothing else changes, including spaces.
Open this step in lesson mode · Link to this step · This confused me
8Project: a coin counter, part 1
Time to put it together. You will build the heart of Beacon Yard's coin system in plain Luau. Part 1: a table of players, and a collect function that adds COIN_VALUE to one player's coins and returns the new total. Two lines are marked TODO. Fill them in, then press Run.
local COIN_VALUE = 5
local coins = {}
local function join(name)
coins[name] = 0
end
local function collect(name)
-- TODO: add COIN_VALUE to this player's coins
-- TODO: return the player's new total
end
join("Player1")
join("Player2")
collect("Player1")
collect("Player1")
local secondTotal = collect("Player2")
print(secondTotal)
print(coins.Player1, coins.Player2)
5
10 5Run the unfinished code first: it prints nil, then 0 0, and fails the check. Fill in the two TODO lines so it prints 5, then 10 5, and passes.
Which two lines inside collect make the program print 5, then 10 5?
local COIN_VALUE = 5
local coins = {}
local function join(name)
coins[name] = 0
end
local function collect(name)
-- TODO
end
join("Player1")
join("Player2")
collect("Player1")
collect("Player1")
local secondTotal = collect("Player2")
print(secondTotal)
print(coins.Player1, coins.Player2)
Answer
coins[name] += COIN_VALUE return coins[name]. coins[name] finds this player's number. += adds to it, and return hands the new total back to the caller.
Open this step in lesson mode · Link to this step · This confused me
9Project: part 2, the shop
Part 2 adds a shop. buy takes a player and an item name. It looks up the price, refuses unknown items and players who cannot afford it, and otherwise takes the coins. It returns true or false and a message, because a function can return more than one value.
local PRICES = { Speed = 25, Shield = 40 }
local coins = { Player1 = 30 }
local function buy(name, item)
local price = PRICES[item]
if price == nil then
return false, `No such item: {item}`
end
if coins[name] < price then
local short = math.max(0, price - coins[name])
return false, `{name} needs {short} more coins for {item}`
end
coins[name] -= price
return true, `{name} bought {item}`
end
print(buy("Player1", "Shield"))
print(buy("Player1", "Speed"))
print(buy("Player1", "Rocket"))
print(coins.Player1)
false Player1 needs 10 more coins for Shield
true Player1 bought Speed
false No such item: Rocket
5This is the same check-before-you-change pattern Beacon Yard's real shop runs on the server: look up, refuse early, and only then subtract.
Put buy's steps in the order the code runs them for a successful purchase.
Answer
1. Look up the item's price 2. Check the item exists 3. Check the player can afford it 4. Subtract the price 5. Return true and a message. Every check happens before any coins move. If a check fails, the function returns early and nothing changes.
Open this step in lesson mode · Link to this step · This confused me
10Project: part 3, the report
Last part: a report that prints every player from richest to poorest. Dictionaries have no order, so collect the names into a list first, then sort the list. table.sort takes a function that says whether a should come before b.
local coins = { Player1 = 5, Player2 = 45, Player3 = 20 }
local names = {}
for name in coins do
table.insert(names, name)
end
table.sort(names, function(a, b)
return coins[a] > coins[b]
end)
for rank, name in names do
print(`{rank}. {name}: {coins[name]}`)
end
1. Player2: 45
2. Player3: 20
3. Player1: 5You just built a tiny leaderboard: the same idea, at a smaller scale, as the leaderstats panel in the top corner of Beacon Yard.
How would you sort the report from poorest to richest instead?
Answer
Change > to < in the sort function. The function answers 'should a come first?'. With <, smaller totals come first.
Open this step in lesson mode · Link to this step · This confused me
11Challenges
Two harder ones to finish. As before, press Run: a hidden test runs against your code, and displays Passed. Every test passed. when it succeeds.
Level 2, Builder
Challenge
Work out how many coins one pad produces in a round, using the respawn time from Beacon Yard's config.
- Start from
- The code cell below the challenge, which runs a hidden test when you press Run.
- Check it here
- Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.
Done means
- A 40-second round gives 11 coins (at 0, 4, 8, ... 40)
- A 3-second round gives 1 coin
- Uses COIN_RESPAWN_SECONDS, not the number 4 written again
Hints
- Count the coin at time 0 separately, or loop from 0 to roundSeconds in steps.
- for t = 0, roundSeconds, COIN_RESPAWN_SECONDS do ... end visits every spawn time.
Solution
local COIN_RESPAWN_SECONDS = 4
local function coinsPerRound(roundSeconds)
local count = 0
for t = 0, roundSeconds, COIN_RESPAWN_SECONDS do
count += 1
end
return count
end
local COIN_RESPAWN_SECONDS = 4
-- Return how many coins one pad produces in a round of roundSeconds,
-- if a coin appears at the start and then every COIN_RESPAWN_SECONDS.
local function coinsPerRound(roundSeconds)
end
Level 3, Professional
Challenge
Find the player with the most coins in a dictionary, with a fair rule for ties.
- Start from
- The code cell below the challenge, which runs a hidden test when you press Run.
- Check it here
- Run the code cell in the lesson view; the challenge completes when it passes. No Studio needed.
Done means
- Finds the highest total
- Breaks ties alphabetically, whatever order the loop visits keys in
- Returns nil for an empty table
Hints
- Keep a bestName and bestCoins as you loop.
- A player wins if they have more coins, or the same coins and a name that sorts first: name < bestName works on strings.
Solution
local function richest(coins)
local bestName = nil
local bestCoins = nil
for name, amount in coins do
if bestName == nil or amount > bestCoins or (amount == bestCoins and name < bestName) then
bestName = name
bestCoins = amount
end
end
return bestName
end
-- Return the name of the player with the most coins.
-- On a tie, return the name that comes first alphabetically.
-- Return nil for an empty table.
local function richest(coins)
end
Open this step in lesson mode · Link to this step · This confused me
12Recap
Retiring the analogy
You no longer need “a name tag stuck on a value”. Variables hold values. Numbers, strings and booleans are copied on assignment, but tables and functions are reference values, so assigning a table copies the reference, not the contents.
Recap
- Tables are lists (numbered from 1, length #t) and dictionaries (key to value, no guaranteed order).
- Assigning a table never copies it: two variables become two name tags on the same table, so edits through either tag are seen by both.
- String interpolation puts expressions inside backticks with {...}, and check-before-you-change guards a shop or coin counter before subtracting.
A variable is a name tag stuck on a value, until two tags can be stuck on the same table, so changing the table through one tag shows through the other, because there is only one table.
Queued for review
Next Reading errors, docs and getting help (including AI as a tutor)
Open this step in lesson mode · Link to this step · This confused me