So far, you have learned how to use for loops in Lua to repeat actions a set number of times or to process each item in a list. You have also discovered how to control these loops with the break statement, allowing you to exit early when needed. Now, let's explore a new kind of loop: the while loop.
The while loop is perfect for situations where you do not know in advance how many times you need to repeat an action. Instead of counting or looping through a list, a while loop keeps running as long as a certain condition is true. This gives you more flexibility and control over your program's flow.
In this lesson, you will learn how to use the while loop to solve problems where the number of repetitions depends on changing conditions. For example, imagine you are planning a trip and want to add countries to your itinerary until your budget runs out. You do not know exactly how many countries you can afford, so a while loop is the right tool for the job.
Here is a sample code snippet to show how this works:
Let's break down what happens in the code above:
travel_budgetis the total amount of money you have for your trip.country_costsis a table that lists how much it costs to visit each country.countries_to_consideris the list of countries you want to visit, in order.total_costkeeps track of how much you have spent so far.chosen_countriesis a list that will store the countries you can afford to visit.iis used to keep track of which country you are currently considering.
The while loop continues as long as you have not spent your entire budget () and there are still countries left to consider (). Inside the loop, the code checks if adding the next country would keep you within your budget. If it does, the country is added to your list and the total cost is updated. The loop then moves on to the next country. When the loop finishes, it prints out the list of countries you can afford to visit.
Understanding while loops is important because many real-world problems do not have a fixed number of steps. You might need to keep asking a user for input until they give a valid answer, keep processing data until a certain condition is met, or keep adding items to a list until you reach a limit.
By mastering while loops, you will be able to write programs that are more flexible and can handle a wider range of situations. This skill will help you solve more complex problems and make your code smarter.
Ready to see how while loops can make your programs more powerful? Let’s move on to the practice section and try it out for yourself!
