Dictionaries and keys
Use a table like a dictionary by storing values under string keys or any other key.
In this page:
Dictionaries and keys
With string keys, t.name and t["name"] are the same thing. The bracket form is needed when the key is not a valid identifier or comes from a variable. Setting a field to nil deletes it. Reading a missing key never raises an error and simply gives nil.
Note:
Use the bracket form for keys held in variables, such as t[key].
Example: Dictionaries and keys
local person = {name = "Ann", age = 30}
person["favorite color"] = "green"
local key = "age"
print(person.name, person[key], person["favorite color"])
person.age = nil
print(person.age)
local t = {}
t[1] = "number"
t["1"] = "string"
print(t[1], t["1"])
-- Output:
-- Ann 30 green
-- nil
-- number string
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing t.key when key is a variable holding the name
- Expecting an error for a missing key
- Thinking t["1"] and t[1] are the same key
Chapter Summary
- t.k equals t["k"]
- Brackets accept any key expression
- Assigning nil removes a key
- "1" and 1 are different keys
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: