← Back to Lua Course | Chapter 4: Tables | Lesson 3 of 7

Dictionaries and keys

Use a table like a dictionary by storing values under string keys or any other key.

In this page:

  1. Dictionaries and keys

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

lua
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
Common Mistakes
  1. Writing t.key when key is a variable holding the name
  2. Expecting an error for a missing key
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.