Taking Tables Further: Working with Nested Tables

You have already learned how to use tables in Lua as lists and as dictionaries. Now, let’s build on that knowledge and explore how tables can contain other tables inside them. This is called using nested tables. Nested tables allow you to organize more complex data, just like folders inside folders on your computer.

What You'll Learn

In this lesson, you will see how to create and use tables that store other tables as their values. This is useful when you need to keep related pieces of information together. For example, imagine you are building a travel application and want to store details about different airport codes, including the city and country for each one.

Here is a sample code snippet:

In this example, each airport code (like JFK or LHR) is a key in the main table. The value for each key is another table that holds the city and country.

Accessing Nested Table Elements

You can access the information inside a nested table by chaining the keys. For example, to get the city and country for LHR:

Dot Notation vs Bracket Notation

In Lua, you can use dot notation (like airport_codes.LHR.city) as a shortcut for bracket notation (like airport_codes["LHR"]["city"]). The dot notation only works when the key is a valid identifier: it must start with a letter or underscore, and can only contain letters, digits, and underscores. For example, airport_codes.LHR is the same as airport_codes["LHR"].

If your key contains spaces, symbols, or starts with a digit, you must use bracket notation with quotes:

Adding a New Nested Element

You can add a new airport code by assigning a new table to a new key:

Updating an Existing Nested Element

You can update the details for an existing airport code by changing the values inside its nested table. For example, to update the country for SYD:

Deleting a Nested Element

To remove an airport code and all its details from the table, set its key to nil:

Visualizing Nested Tables

Here’s a simple diagram to help you picture how nested tables work in Lua:

Each key (like JFK) in the main table points to a sub-table, which contains its own keys (city and country) and their values.

Why Nested Tables Matter

Nested tables are important because real-world data is often complex and connected. By learning how to use tables inside tables, you can model things like user profiles, product catalogs, or travel information in a clear and organized way. This skill will help you write programs that are more powerful and easier to manage.

Ready to practice? Let’s dive in and see how nested tables can make your Lua programs even more useful!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal