Combining Conditionals and Tables
Bringing Conditionals and Data Structures Together
In the previous lessons, you learned how to use if, elseif, and logical operators to make decisions in your Lua programs. Now, let's take things further by combining these decision-making tools with data structures — specifically, tables. This is a key step in writing programs that can handle more complex, real-world information.
What You'll Learn
In this lesson, you will see how to use tables (Lua’s main data structure) together with conditional statements. This allows you to store and check information about many items at once and then make decisions based on that data.
For example, imagine you are keeping track of the countries you want to visit and whether you have already been there. You can store this information in a table and use an if statement to check if a destination is new or already visited:
In this code, we use a table to store information about each country. The if statement checks if the destination exists in the table and whether it has been visited, then prints a message based on the result.
Expected Output:
Explanation:
- The variable
destinationis set to"France". travel_destinations["France"]exists, so the first part of theifcondition is true.- However,
travel_destinations["France"].visitedisfalse, so the firstifblock is skipped. - The
elseifcondition checks iftravel_destinations["France"]exists, which it does, so this block runs. - The message printed uses the capital from the table (
Paris) and tells the user they haven't visited France yet. - The
elseblock is not executed because the destination exists in the table.
Why This Matters
