Lua Tables as Dictionaries
A dictionary (also called a map or hash) stores values under keys that aren't positions: names, IDs, words. In Lua it is simply a table with non-sequence keys, usually strings.
local capitals = {
France = "Paris",
Japan = "Tokyo",
Kenya = "Nairobi",
}
print(capitals.Japan)
print(capitals["Kenya"])
capitals.Peru = "Lima" -- add
capitals.France = "PARIS" -- update
capitals.Japan = nil -- remove
print(capitals.France, capitals.Peru, capitals.Japan)Tokyo
Nairobi
PARIS Lima nil
Dot vs brackets
t.name is shorthand for t["name"], and only works when the key is a valid identifier written literally. Use brackets for keys with spaces or symbols, keys that are not strings, and keys stored in variables:
local scores = { ["Mary Ann"] = 12, [404] = "not found" }
local who = "Mary Ann"
print(scores[who]) -- variable key: brackets
print(scores[404])
print(scores.who) -- looks up the literal key "who"!12
not found
nil
scores.who is a classic bug: it reads the key "who", not the value of the variable who.
Iterating with pairs
pairs(t) visits every key-value pair, but in no particular order. For predictable output, sort the keys first:
local inventory = { sword = 1, potion = 5, arrow = 30, shield = 1 }
local keys = {}
for item in pairs(inventory) do
keys[#keys + 1] = item
end
table.sort(keys)
for _, item in ipairs(keys) do
print(string.format("%-7s %3d", item, inventory[item]))
endarrow 30
potion 5
shield 1
sword 1
Counting things
Dictionaries are perfect for counting. counts[word] = (counts[word] or 0) + 1 handles the first occurrence, when the key is still nil:
local text = "the cat and the hat and the bat"
local counts = {}
for word in text:gmatch("%a+") do
counts[word] = (counts[word] or 0) + 1
end
local words = {}
for w in pairs(counts) do words[#words + 1] = w end
table.sort(words, function(a, b)
if counts[a] ~= counts[b] then return counts[a] > counts[b] end
return a < b
end)
for _, w in ipairs(words) do print(w, counts[w]) endthe 3
and 2
bat 1
cat 1
hat 1
Size of a dictionary
# doesn't count dictionary keys. Count them with a loop, and test emptiness with next:
local function size(t)
local n = 0
for _ in pairs(t) do n = n + 1 end
return n
end
local config = { debug = true, port = 8080, host = "localhost" }
print(#config, size(config))
print(next({}) == nil, next(config) ~= nil)0 3
true true
next(t) returns the first key of a table (or nil if it is empty); it is what pairs uses internally.
Sets
A set is a dictionary whose values are just true. Membership tests are instant, no matter how big the set is:
local function Set(list)
local s = {}
for _, v in ipairs(list) do s[v] = true end
return s
end
local reserved = Set { "and", "end", "local", "while" }
for _, word in ipairs({ "local", "speed", "end" }) do
print(word, reserved[word] and "reserved" or "ok")
endlocal reserved
speed ok
end reserved
Printing a table's contents
Here is a small, reusable dump that prints any nested table with sorted keys, so the output is the same on every run:
local function dump(value, indent)
indent = indent or ""
if type(value) ~= "table" then
return type(value) == "string" and string.format("%q", value) or tostring(value)
end
local keys = {}
for k in pairs(value) do keys[#keys + 1] = k end
table.sort(keys, function(a, b) return tostring(a) < tostring(b) end)
local lines = { "{" }
for _, k in ipairs(keys) do
lines[#lines + 1] = indent .. " " .. tostring(k) .. " = " .. dump(value[k], indent .. " ") .. ","
end
lines[#lines + 1] = indent .. "}"
return table.concat(lines, "\n")
end
print(dump({ name = "Rex", age = 4, tags = { "good", "dog" }, owner = { city = "Oslo" } })){
age = 4,
name = "Rex",
owner = {
city = "Oslo",
},
tags = {
1 = "good",
2 = "dog",
},
}
Test yourself
Given local k = "x", which expression reads the value stored under key "x"?
t.kt[k]t:kt->k
What does #t return for t = { a = 1, b = 2 }?
20nil- An error
How do you test whether a table is empty?
#t == 0t == {}next(t) == nilt.empty