Skip to content
Tables as Dictionaries
step 1/5

Reading — step 1 of 5

Learn

~1 min readTables — The One Data Structure

Use a table with string keys as a dictionary. Two equivalent syntaxes:

local user = { name = "Ada", age = 36 }
-- same as:
local user = {}
user["name"] = "Ada"
user["age"]  = 36
user.name              -- shorthand for user["name"]

for key, value in pairs(user) do
    print(key, value)
end

pairs iterates ALL keys in arbitrary order. ipairs only walks the sequence (integer keys).

Delete a key by setting it to nil:

user.age = nil

A missing key returns nil — useful for the default idiom: local v = t[k] or default.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…