Tables as Dictionaries & Hash Maps

Tables as Dictionaries & Hash Maps in Lua: When keys are strings, booleans, or other objects, Lua tables function as high-speed Hash Maps.

When keys are strings, booleans, or other objects, Lua tables function as high-speed Hash Maps. Under the hood, Lua stores tables using a hybrid structure: an array part for contiguous integer keys and a hash part for arbitrary key-value pairs.


Hash Map Syntax: Dot vs Bracket Notation

local character = {
    name = "Kaelen",
    class = "Paladin",
    level = 60,
    ["special status"] = "Blessed" -- Bracket notation allows spaces or special chars
}

-- Dot notation (equivalent to character["name"])
print(character.name) 

-- Bracket notation for dynamic keys:
local field = "level"
print(character[field]) -- 60

-- Adding new fields
character.guild = "Knights of the Silver Hand"

-- Deleting fields: Setting to nil removes the key entirely!
character.class = nil

Iterating Arbitrary Keys with pairs and next

Unlike ipairs which only checks sequential numbers, pairs traverses every key in the table (including strings, negative numbers, and non-contiguous keys):

local telemetry = {
    cpu_usage = 0.42,
    memory_mb = 1024,
    cluster_id = "us-east-1",
    active = true
}

for key, value in pairs(telemetry) do
    print(tostring(key) .. " => " .. tostring(value))
end

Behind the scenes, pairs(t) is implemented using the built-in next function:

-- Manual table traversal using next:
local k, v = next(telemetry, nil) -- Start at the beginning
while k do
    print("Key: " .. k)
    k, v = next(telemetry, k)     -- Get next key after k
end

Checking Key Existence vs Nil Values

Because missing keys return nil, checking if a key exists requires care when the value itself might be stored as nil or false:

local flags = { pvp_enabled = false }

-- WRONG: flags.pvp_enabled is false, so this branch won't execute!
if flags.pvp_enabled then
    print("Flag is set")
end

-- CORRECT: Explicit nil comparison checks if the key exists
if flags.pvp_enabled ~= nil then
    print("Flag exists and is set to boolean: " .. tostring(flags.pvp_enabled))
end

Memory Pre-Allocation in LuaJIT / Lua 5.4

In performance-critical loops (e.g., game rendering frames), dynamically growing a table forces the Lua allocator to repeatedly resize the internal hash table and rehash all keys.

Pre-populating tables or reusing tables (object pooling) prevents garbage collection spikes:

-- Object Pool pattern: Reuse table to avoid GC pressure
local bulletPool = {}
for i = 1, 100 do
    bulletPool[i] = { x = 0, y = 0, active = false }
end

Exercises

  1. Write a deep copy function that clones nested tables without circular reference errors.
  2. Implement a word-frequency counter that reads a string and returns a table mapping words to occurrence counts.
  3. Explain why modifying keys during a pairs iteration can cause unpredictable traversal behavior in Lua.