0Pricing
Lua Academy · Lesson

Tables as Dictionaries

Use string and mixed keys to store key-value pairs.

Tables as Dictionaries is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

String Keys

Tables with string keys act as dictionaries (hash maps). Access fields using dot notation t.key (for valid identifiers) or bracket notation t["key"] (for any string). Both forms are equivalent; bracket notation supports dynamic keys.

local user = {}
user.name = "Alice"
user["age"] = 30
user.role = "admin"

print(user.name)        -- Alice
print(user["age"])      -- 30

local field = "role"
print(user[field])      -- admin (dynamic key)

Table Literals

Dictionaries can be initialized with a table literal using key = value syntax. This is the most common way to create records in Lua. You can mix array-style and dictionary-style entries in one literal.

local config = {
  host = "localhost",
  port = 3306,
  database = "myapp",
  debug = false,
  tags = {"web", "api"},  -- nested array
}

print(config.host)        -- localhost
print(config.port)        -- 3306
print(config.tags[1])     -- web

Counting with Dictionaries

A classic dictionary use case is frequency counting. Iterate over a list, using each element as a key and incrementing the count. Check for nil before incrementing — use count[word] or 0 as the initial value.

local words = {"lua","is","fast","lua","is","lua"}
local freq = {}

for _, w in ipairs(words) do
  freq[w] = (freq[w] or 0) + 1
end

for word, count in pairs(freq) do
  print(word, count)
end
-- lua 3, is 2, fast 1

Grouping with Dictionaries

Grouping data by a property: iterate the list and use the grouping key to append items to a list in a dictionary. This is the Lua equivalent of SQL GROUP BY or Python's defaultdict pattern.

local people = {
  {name="Alice", dept="eng"},
  {name="Bob",   dept="hr"},
  {name="Carol", dept="eng"},
  {name="Dave",  dept="hr"},
}
local groups = {}

for _, p in ipairs(people) do
  local d = p.dept
  groups[d] = groups[d] or {}
  groups[d][#groups[d]+1] = p.name
end

print(table.concat(groups.eng, ", "))  -- Alice, Carol

Checking Key Existence

Test whether a key exists by comparing its value to nil. Be careful: if the value stored at a key is nil, the key is considered absent. For presence flags, store true as the value instead of nil.

local cache = {result=42, mode="fast"}

if cache.result ~= nil then
  print("cached:", cache.result)  -- 42
end

-- Key not present:
if cache.timeout == nil then
  print("no timeout set")
end

-- Membership set pattern
local allowed = {admin=true, editor=true}
if allowed["admin"] then
  print("access granted")
end

Deleting Keys

Set a table key to nil to remove it. The key-value pair disappears and the garbage collector can reclaim the value's memory. You cannot delete a local variable this way — only table entries.

local session = {token="abc123", user="Alice", expires=3600}
print(session.token)   -- abc123

session.token = nil
print(session.token)   -- nil (removed)

-- Count remaining keys
local count = 0
for _ in pairs(session) do count = count + 1 end
print(count)   -- 2

Merging Dictionaries

Merge two tables by iterating one and copying its entries into the other. If both have the same key, the second table's value wins. This is Lua's equivalent of JavaScript's Object.assign.

local defaults = {color="blue", size=12, bold=false}
local overrides = {color="red", italic=true}

local function merge(base, over)
  local result = {}
  for k, v in pairs(base) do result[k] = v end
  for k, v in pairs(over) do result[k] = v end
  return result
end

local opts = merge(defaults, overrides)
print(opts.color, opts.size, opts.italic)  -- red 12 true

Any Key Type

Table keys can be any non-nil, non-NaN value: strings, numbers, booleans, functions, and even other tables. Integer keys and string keys are stored differently internally, but accessed uniformly with bracket notation.

local t = {}
local function myKey() end

t["string"] = 1
t[42] = 2
t[true] = 3
t[myKey] = 4

print(t["string"])  -- 1
print(t[42])        -- 2
print(t[true])      -- 3
print(t[myKey])     -- 4

Ordered Iteration

Lua's pairs() does not guarantee iteration order. To iterate in a defined order, collect the keys into an array, sort it, then iterate.

local scores = {Alice=95, Bob=87, Carol=91, Dave=78}

local names = {}
for name in pairs(scores) do
  names[#names+1] = name
end
table.sort(names)

for _, name in ipairs(names) do
  print(name, scores[name])
end
-- Alice 95, Bob 87, Carol 91, Dave 78 (sorted)

Default Values Pattern

A useful pattern is a "defaults" table accessed via __index metatable. When a key is not found in the main table, Lua looks it up in the defaults table. This enables layered configuration without merging.

local defaults = {timeout=30, retries=3, verbose=false}
local config = {timeout=60}

setmetatable(config, {__index = defaults})

print(config.timeout)  -- 60  (overridden)
print(config.retries)  -- 3   (from defaults)
print(config.verbose)  -- false (from defaults)

Quick Check

How do you remove a key "x" from table t in Lua?

Recap: Tables as Dictionaries

Key points:

  • Dot and bracket notation: t.key == t["key"]
  • Any non-nil, non-NaN value can be a key
  • Set to nil to delete a key
  • Frequency counting: t[k] = (t[k] or 0) + 1
  • Ordered iteration: collect keys → sort → iterate
  • Use __index metatable for default values

Frequently asked questions

Is the “Tables as Dictionaries” lesson free?

Yes — the full text of “Tables as Dictionaries” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Tables as Dictionaries”?

Use string and mixed keys to store key-value pairs. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Tables as Dictionaries” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Tables as Arrays
  2. Tables as Dictionaries
  3. Iterating Tables with pairs and ipairs
  4. Nested Tables and Structured Data
← Back to Lua Academy