Lua Table Dictionaries
A dictionary table is a table that stores values under named keys instead of numbered slots. Each key points to one value.
Lookups read values by key
Each key names one price. The prints read three values by their keys.
local prices = {bread = 2, milk = 3, eggs = 4}
print(prices.bread)
print(prices["milk"])
print(prices.eggs)Assign nil to remove a key
A new key is added by assigning to it. Assigning nil to a key removes it, and reading it then gives nil.
local prices = {bread = 2, milk = 3}
prices.eggs = 4
prices.milk = nil
print(prices.eggs)
print(prices.milk)
print(prices.bread)Count keys with a pairs loop
pairs visits every key in the table. Counting the visits gives the number of keys, whatever order they are visited in.
local prices = {bread = 2, milk = 3, eggs = 4, cheese = 5}
local count = 0
for k, v in pairs(prices) do
count = count + 1
end
print(count)Example
local phone = {sam = "555-01", ana = "555-02", lee = "555-03"}
print(phone.sam)
phone.ana = "555-22"
print(phone.ana)
phone.lee = nil
print(phone.lee)
local count = 0
for k, v in pairs(phone) do
count = count + 1
end
print(count)Key points
- Dictionary: A dictionary table stores a value under each named key.
- Key: A key is the name used to find a value in the table.
- Lookup: Write prices.milk or prices["milk"] to read the value stored under a key.
- Add: Assigning to a new key adds that key and its value to the table.
- Remove: Assigning nil to a key removes that key from the table.
- Missing key: Reading a key that is not in the table gives nil.
In this example, the phone book stores one number under each name and the first print looks up the number for sam. The number for ana is then replaced by a new assignment. The entry for lee is removed by assigning nil, the next print shows nil, and a pairs loop counts the two keys left.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you remove the key "milk" from the table prices?