Look Up Values by Name

So far, every table index has been a number. An index does not have to be a number. It can also be a string. With string indexes, a table works as a dictionary: you look up a value by its name instead of its position. In a dictionary, the index is usually called a key.

local ages = {}
ages["Alice"] = 30
ages["Bob"] = 25
print(ages["Alice"])
print(ages["Emma"])

Output:

30
nil

ages["Alice"] = 30 stores 30 under the key "Alice". ages["Alice"] reads it back. Nobody stored a value for "Emma", so that lookup gives nil, just like a missing index in a list.

The dot form

When a key could also work as a variable name, like Bob, there is a shorter way to write it. ages.Bob means exactly the same as ages["Bob"].

You can also put keys in the curly braces when you create the table, with key = value:

local ages = {Alice = 30, Bob = 25}
ages.Emma = 22
print(ages.Bob, ages.Emma)

Output:

25	22

Keys in variables need brackets

Often the key is not known when you write the code. It comes from input, or from a variable. Then you must use square brackets:

local ages = {Alice = 30, Bob = 25}
local name = io.read()
print(ages[name])
print(ages.name)

Output:

25
nil

The input was Bob. ages[name] uses the value of the variable name, which is "Bob", so it finds 25. But ages.name looks for a key that is literally called "name". There is no such key, so you get nil.

So the rule is: use the dot when you know the key while writing the code. Use brackets when the key is in a variable.

Remove a key

To remove a key, set it to nil:

local ages = {Alice = 30, Bob = 25}
ages.Bob = nil
if ages.Bob then
    print("Bob is here")
else
    print("Bob is gone")
end

Output:

Bob is gone

A missing key gives nil, and nil counts as false in an if. So if ages.Bob then is a simple way to check if a key exists.

To go through all the keys of a dictionary, you need a different kind of loop. That is the next lesson.

In the exercise, add two fruits to a price list, so the program can look up the price of any fruit in the input.