Tables, lesson 17
Dictionaries
Goal: Look values up by name.
about 5 min3 practice exercises
An array finds values by position. A dictionary finds them by name, called a key.
local coinValues = {
Bronze = 1,
Silver = 5,
Gold = 25,
}
print(coinValues.Gold) -- 25
print(coinValues["Silver"]) -- 5
coinValues.Gold and coinValues["Gold"] mean the same thing. The bracket form is the one to use when the key is in a variable:
local coinType = "Silver"
print(coinValues[coinType]) -- 5
Add or change an entry by assigning to it. Remove one by setting it to nil:
coinValues.Diamond = 100
coinValues.Bronze = nil
A key that is not in the table gives nil. That is how you check a value is valid before using it:
local value = coinValues[coinType]
if value then
print("Worth " .. value)
end
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.