Tables are the cornerstone of Lua programming, serving as the language's primary data structure. They're incredibly versatile, functioning as arrays, dictionaries, and objects.
Lua tables are associative arrays that can store various types of data, including numbers, strings, booleans, and even other tables or functions. They're the only data structuring mechanism in Lua, making them essential for organizing and manipulating data efficiently.
To create a table in Lua, use curly braces {}
. Here's a simple example:
local myTable = {}
You can also initialize a table with values:
local fruits = {"apple", "banana", "cherry"}
Access table elements using square brackets []
or dot notation for string keys. Here are some examples:
local person = {name = "Alice", age = 30}
print(person["name"]) -- Output: Alice
print(person.age) -- Output: 30
person.job = "Developer" -- Adding a new key-value pair
person["salary"] = 50000 -- Another way to add a key-value pair
Lua tables can function as arrays, with integer indices starting from 1. Learn more about this in our Lua Tables as Arrays guide.
local numbers = {10, 20, 30, 40, 50}
print(numbers[1]) -- Output: 10
print(#numbers) -- Output: 5 (length of the table)
Tables also serve as dictionaries or associative arrays. Explore this further in our Lua Tables as Dictionaries article.
local scores = {math = 95, science = 88, history = 92}
print(scores.math) -- Output: 95
#
operator returns the length of a sequence in a table, but it may not work as expected for tables with non-sequential keys.Mastering Lua tables is crucial for effective Lua programming. They offer a flexible and powerful way to structure data, forming the foundation for more complex data manipulations and algorithms.
To deepen your understanding, explore our guides on table manipulation and table sorting. For those interested in object-oriented programming in Lua, our OOP concepts guide demonstrates how tables can be used to implement classes and objects.