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
Step 1 of 12
Tables 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.
pads[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])
Press 1 to 4 to choose, Enter to check.
Step 2 of 12
Visit 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.
_ 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)
Press 1 to 4 to choose, Enter to check.
Step 3 of 12
Tables 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.
That 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)
Press 1 to 4 to choose, Enter to check.
Step 4 of 12
Visit 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.
This 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?
Press 1 to 4 to choose, Enter to check.
Step 5 of 12
Tables 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.
This crashes with: attempt to index nil with 'coins'. Fix it so Player3 starts with 0 coins and the program prints 5.
Press 1 to 4 to choose, Enter to check.
Step 7 of 12
Building 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.
The 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`)
Press 1 to 4 to choose, Enter to check.
Step 8 of 12
Project: 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.
Run 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)
Press 1 to 4 to choose, Enter to check.
Step 9 of 12
Project: 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.
This 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.
- Check the player can afford it
- Subtract the price
- Return true and a message
- Look up the item's price
- Check the item exists
Step 10 of 12
Project: 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.
You 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?
Press 1 to 4 to choose, Enter to check.
Step 11 of 12
Challenges
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; 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
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; 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
Step 12 of 12
Recap
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)