Skip to content
AgileLogics
4 min read

Dictionaries and Records

Prerequisites: Tables: the one data structure

A table with string keys works as a dictionary (look up values by key) or a record (an object with named fields).

local ages = {Ada = 36, Linus = 28}

ages.Grace = 45
ages["Linus"] = 29
ages.Ada = nil

print(ages.Linus)
print(ages.Ada)
print(ages["Grace"])

local name = "Grace"
print(ages[name])
print(ages.name)
29
nil
45
45
nil

Note the last two lines: ages[name] uses the value of the variable name as the key; ages.name means the literal key "name".

Checking and counting

local stock = {apples = 10, pears = 0}

if stock.pears ~= nil then print("pears are tracked") end
if stock.plums == nil then print("no plums entry") end

local count = 0
for _ in pairs(stock) do count = count + 1 end
print("entries: " .. count)
pears are tracked
no plums entry
entries: 2

# doesn't count string keys — count with a loop.

Nested records

local config = {
  server = {host = "localhost", port = 8080},
  debug = true,
  admins = {"ada", "linus"},
}

print(config.server.port)
print(config.admins[2])
config.server.port = 9090
print(config.server.port)
print(config.database and config.database.name)
8080
linus
9090
nil

Accessing a field of a missing table (config.database.name) is an error; config.database and config.database.name safely returns nil.

Sets

local tags = {lua = true, games = true}
tags.neovim = true
print(tags.lua)
print(tags.python)
true
nil

Using values as keys with true gives a fast set: membership is a single lookup.