0Pricing
Lua Academy · Lesson

Tables as Dictionaries

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

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

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