Nested Tables in Lua

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:

local airport_codes = {
    JFK = {city = "New York", country = "USA"},
    LAX = {city = "Los Angeles", country = "USA"},
    LHR = {city = "London", country = "UK"},
    HND = {city = "Tokyo", country = "Japan"},
    SYD = {city = "Sydney", country = "Australia"}
}

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:

print(airport_codes.LHR.city .. " - " .. airport_codes.LHR.country)  -- Output: London - UK

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:

local airport_codes = {
    JFK = {city = "New York", country = "USA"},
    ["123ABC"] = {["city name"] = "Test City", country = "Testland"}
}

print(airport_codes.JFK.city)  -- Output: New York
print(airport_codes["JFK"]["city"])  -- Output: New York

print(airport_codes["123ABC"]["city name"])  -- Output: Test City
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