Welcome to your first step into the world of data structures in Lua! In this lesson, you will learn about tables, which are the most important and flexible data structure in Lua. If you have programmed in other languages, you might know similar structures as arrays or lists. Here, we will focus on how to use tables as lists to store and access collections of items.
In this lesson, you will discover how to create a table in Lua and use it as a list. You will learn how to store multiple values, such as travel destinations, in a single table. You will also see how to access specific items in your list using Lua’s 1-based indexing (which means counting starts at 1, not 0).
For example, here is how you can create a table of travel destinations and access the first and last items:
Let’s break this down:
- We create a table called
travel_destinationswith five cities. - We access the first city using
travel_destinations[1]. - We use the
#operator to get the number of items in the table, which helps us find the last city.- Note: The
#operator works reliably only when your table is a proper sequence—meaning it has consecutive integer keys from 1 up to its length, with no gaps (nonilvalues in between). If there are missing items (holes) in the table, the result of#may not be what you expect.
- Note: The
Tables are the foundation of almost everything you will do in Lua. Whether you are building a simple list of names or managing more complex data, understanding tables will make your programs more powerful and flexible. By learning how to create and access tables, you are building skills that will help you organize and process information efficiently in your Lua projects.
Are you ready to get started? Let’s move on to the practice section and try it out for yourself!
