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.

Lab lesson, about 70 minutes, 12 steps

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.

Luau
local pads = {"Pad1", "Pad2", "Pad3"}
print(pads[1], pads[3])
print(#pads)
 
table.insert(pads, "Pad4")
print(#pads, pads[4])
print(pads[10])
Figure 1.1. Expected output: Pad1 Pad3 3 4 Pad4 nil

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])
  1. Alpha
  2. Bravo
  3. nil
  4. an error
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.

Luau
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)
Figure 2.1. Expected output: 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)
  1. 100
  2. 60
  3. 40
  4. 85
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.

Luau
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)
Figure 3.1. Expected output: 25 40 Shield costs 40 60 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,
Figure 3.2

What does this print?

local Config = { COIN_VALUE = 5, WRENCH_RANGE = 14 }
local key = "WRENCH_RANGE"
print(Config[key] - Config.COIN_VALUE)
  1. 9
  2. 19
  3. nil
  4. an error
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.

Luau
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)
Figure 4.1. Expected output: 2 items, total 65

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?

  1. Always Speed, Shield, Magnet: the order you wrote
  2. Always alphabetical
  3. The order is not guaranteed, so code must not depend on it
  4. Always sorted by price
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.

Luau
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)
Figure 5.1. Expected output: 5 30 true nil

This 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

6Where the name tag idea breaks

Name tags have worked well so far. Moving a tag never changed the value it left behind. Now look at this, and decide what it prints before you run it.

Where does it break?“A name tag stuck on a value” is a good picture of a variable. Where does it stop being true?

It breaks here. 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.

The true model. 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.

What does this print?

local mine = { coins = 5 }
local copy = mine
copy.coins = 99
print(mine.coins)
  1. 5
  2. 99
  3. nil
  4. an error
Answer

99. copy = mine does not copy the table. It sticks a second tag on the same table. Change it through either tag, and both see the change.

Luau
local mine = { coins = 5 }
local copy = mine
copy.coins = 99
print(mine.coins)
 
local n = 5
local m = n
m = 99
print(n)
Figure 6.1. Expected output: 99 5

Numbers, strings and booleans behave like separate copies: m = 99 moves only the m tag. A table is one object, and every variable you assign it to is another tag on the same table. This matters in Beacon Yard. When two scripts hold the same player profile table, a change made by one is seen by the other.

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.

Luau
local name = "Player1"
local coins = 45
print(`{name} has {coins} coins`)
print(`Shield in {40 - coins} coins`)
print(`Can buy shield: {coins >= 40}`)
Figure 7.1. Expected output: Player1 has 45 coins Shield in -5 coins Can buy shield: true

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`)
  1. Pad{pad} has {pad * 5} coins
  2. Pad3 has 15 coins
  3. Pad 3 has 15 coins
  4. an error
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.

Luau
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)
Figure 8.1. Expected output: 5 10 5

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)
  1. coins[name] += COIN_VALUE return coins[name]
  2. coins[name] = COIN_VALUE return coins[name]
  3. coins[name] += COIN_VALUE print(coins[name])
  4. return coins[name] + COIN_VALUE
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.

Luau
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)
Figure 9.1. Expected output: false Player1 needs 10 more coins for Shield true Player1 bought Speed false No such item: Rocket 5

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.

  1. Check the player can afford it
  2. Subtract the price
  3. Return true and a message
  4. Look up the item's price
  5. Check the item exists
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.

Luau
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
Figure 10.1. Expected output: 1. Player2: 45 2. Player3: 20 3. Player1: 5

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?

  1. Change > to < in the sort function
  2. Loop over names backwards with a while loop
  3. Change table.sort to table.insert
  4. It is impossible with table.sort
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

  1. Count the coin at time 0 separately, or loop from 0 to roundSeconds in steps.
  2. for t = 0, roundSeconds, COIN_RESPAWN_SECONDS do ... end visits every spawn time.
Solution
luau
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
Luau
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
Figure 11.1. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. Keep a bestName and bestCoins as you loop.
  2. A player wins if they have more coins, or the same coins and a name that sorts first: name < bestName works on strings.
Solution
luau
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
Luau
-- 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
Figure 11.2. Run it in the lesson view or in the Studio command bar. The lesson view checks it with tests.

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

  1. Tables are lists (numbered from 1, length #t) and dictionaries (key to value, no guaranteed order).
  2. 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.
  3. 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.

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