In the previous lesson, you learned how to create tables in Lua and use them as lists to store and access collections of items, such as travel destinations. You saw how to get the first and last items from a table using Lua’s 1-based indexing and the # operator. Now that you know how to create and read from tables, it’s time to learn how to change them — by adding and removing elements.
In this lesson, you will discover how to make your tables more dynamic. You will learn how to add new items to a table, remove items you no longer need, and even insert items at specific positions. These skills are essential for any program that needs to update its data as things change.
For example, imagine you are planning a world tour and want to update your list of countries as your plans change. Here’s a quick look at how you might do this in Lua:
Let’s break this down:
table.insert(world_tour_countries, "Australia")adds a new country to the end of the list.table.insert(world_tour_countries, 1, "Japan")inserts "Japan" at the start of the list (position 1), and moves all other items one position forward. You can use any valid position to insert an item exactly where you want it.table.remove(world_tour_countries, 4)deletes the country at position 4 ("Brazil" in this case) from the list.
Note, when you use table.remove(world_tour_countries, 4), Lua deletes the country at position 4 and then shifts all the elements after that position one place to the left. This means there are no empty spots (no nil values) left in the middle of the table—the list stays compact and continuous.
After making changes to your table, you might want to see all the items it contains. In Lua, you can print each item in a table using a for loop. Here’s how you can print the entire world_tour_countries list:
Don’t worry if you’re not familiar with the for loop yet—we’ll explain how it works in later in the learning path. For now, you can just use this block of code whenever you want to print all the items in your list.
Being able to add and remove items from tables is a key skill for any Lua programmer. Real-world programs often need to update their data as users interact with them or as new information becomes available. Whether you are building a travel planner, a game inventory, or a contact list, knowing how to manipulate tables will help you create flexible and useful programs.
Ready to put these new skills into practice? Let’s move on and try them out together!
