Now that you have learned how to use both for and while loops in Lua, it is time to take your skills a step further. In this lesson, you will explore how to use loops inside other loops — these are called nested loops. This is a natural next step after learning about single loops, and it will help you handle more complex data and tasks in your programs.
Nested loops are useful when you need to work with multiple sequences or layers of information at the same time. For example, imagine you are planning a trip and, for each country you visit, you want to list the sights you want to see. You have a table in which each country is linked to a list of sights. To print out all the sights for every country, you need a loop inside another loop.
Here is a sample code snippet to show how this works:
Let's break down what happens in the code above:
- The variable
country_sightsis a table where each key is a country and each value is a list (table) of sights in that country. - The outer
forloop usespairsto go through each country and its list of sights. - For each country, the code prints a header line showing the country name.
- The inner
forloop usesipairsto go through the list of sights for the current country. - Each sight is printed on its own line.
This structure allows you to process and display information that is organized in layers — in this case, countries and their sights. The outer loop handles the first layer (countries), and the inner loop handles the second layer (sights within each country). Nested loops like this are a powerful way to work with grouped or hierarchical data in Lua.
-
pairsis used to iterate over all key-value pairs in a table, no matter what the keys are (they can be strings or numbers, and in any order). In our example,country_sightsuses country names as keys, so we usepairs(country_sights)to go through each country and its list of sights. -
ipairsis used to iterate over tables that act like arrays, where the keys are consecutive integers starting from 1. It goes through the elements in order and stops at the firstnilvalue. In our example, each value incountry_sightsis a list of sights, so we useipairs(sights)to go through each sight in order.
Nested loops are important because many real-world problems involve working with data that is grouped or organized in multiple levels. For example, you might need to process a list of students and, for each student, a list of their grades. Or you might want to display a calendar with weeks and days. By learning how to use nested loops, you will be able to write code that can handle these situations with ease.
Are you ready to practice using nested loops and see how they can help you manage more complex tasks? Let’s get started!
