So far, you have learned how to use tables in Lua as lists — collections of items you can access by their position. Now, let’s take your skills a step further. In this lesson, you will see how tables can also be used as dictionaries, where each item is stored as a pair: a key and a value. This is a powerful way to organize and look up information quickly, just like using a real-world dictionary to find the meaning of a word.
You will learn how to create tables that use custom keys (such as country names) instead of just numbers. This allows you to store and retrieve information in a more meaningful way. For example, you can use a table to map countries to their capital cities:
With this table, you can easily look up the capital of any country by its name:
For simple string keys (that are valid identifiers), you can use a shorthand without brackets and quotes:
Both forms work the same way, so you can choose whichever style you prefer for your tables.
You will also learn how to add new pairs, update existing ones, and remove pairs from your table. For example, you can add the USA and its capital, or remove Kenya from the table:
Each line in these examples has a specific purpose:
- The first snippet creates a table with country-capital pairs.
- The second snippet shows how to access a value using its key.
- The third snippet demonstrates how to add a new pair and remove an existing one by setting its key to
nil.
Using tables as dictionaries is essential for organizing and managing data in Lua. This approach is used everywhere — from storing user profiles in apps to keeping track of scores in games. By mastering this skill, you will be able to build programs that are smarter and more efficient, making it easy to find and update information as your program runs.
Let’s get started and see how you can use tables as dictionaries in your own Lua projects!
