Tables, lesson 19
Tables of tables
Goal: Describe your game's items as data.
about 6 min3 practice exercises
Tables can hold other tables. This is how real game data is organized: one table per thing, grouped in a bigger table.
local COINS = {
Bronze = { value = 1, respawn = 5 },
Silver = { value = 5, respawn = 15 },
Gold = { value = 25, respawn = 60 },
}
print(COINS.Gold.value) -- 25
print(COINS.Silver.respawn) -- 15
Read it left to right: COINS.Gold is the inner table, and .value is a field in it.
Now the rest of your code needs no numbers of its own:
local function coinsFor(coinType)
local info = COINS[coinType]
if not info then
return 0
end
return info.value
end
print(coinsFor("Gold")) -- 25
print(coinsFor("Rubber")) -- 0
To rebalance the game you edit one table. This is called a config table, and nearly every well made Roblox game has them.
One thing to remember: assigning a table to another variable does not copy it. Both names point at the same table, so a change through one shows through the other.
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.