Tables are the only data structure available in Lua and are incredibly versatile. They can be used to represent arrays, dictionaries, records, and more.
A table in Lua is created using curly braces `{}`. Here is a simple table with some fruits.
fruits = {"apple", "banana", "mango"}
You can access elements in the table using their indices. Lua tables are 1-based.
print(fruits[1]) -- Output: apple print(fruits[2]) -- Output: banana print(fruits[3]) -- Output: mango
To add elements to a table, you can use the `table.insert` function. To remove elements, use the `table.remove` function.
table.insert(fruits, "orange") print(fruits[4]) -- Output: orange table.remove(fruits, 2) -- Removes "banana" print(fruits[2]) -- Output: mango
You can also have tables without numeric indices. These are often referred to as dictionaries or maps.
person = { name = "John", age = 30, city = "Jakarta" }
Access elements in the table using their keys.
print(person.name) -- Output: John print(person.age) -- Output: 30 print(person.city) -- Output: Jakarta
Tables can have both indexed and named elements.
mixedTable = { "apple", "banana", name = "Fruit Basket", count = 2 } print(mixedTable[1]) -- Output: apple print(mixedTable[2]) -- Output: banana print(mixedTable.name) -- Output: Fruit Basket print(mixedTable.count) -- Output: 2
You can iterate over indexed tables using `ipairs` and over all elements (indexed and named) using `pairs`.
-- Iterating over indexed elements for i, fruit in ipairs(fruits) do print("Fruit " .. i .. ": " .. fruit) end -- Iterating over all elements for key, value in pairs(person) do print(key .. ": " .. value) end
Tables can contain other tables, allowing you to create complex data structures.
nestedTable = { fruits = {"apple", "banana"}, vegetables = {"carrot", "lettuce"} } print(nestedTable.fruits[1]) -- Output: apple print(nestedTable.vegetables[2]) -- Output: lettuce
Lua provides several built-in functions for table manipulation.
-- Sorting a table numbers = {5, 2, 9, 1, 5, 6} table.sort(numbers) for i, num in ipairs(numbers) do print(num) end -- Output: -- 1 -- 2 -- 5 -- 5 -- 6 -- 9 -- Concatenating table values into a string str = table.concat(fruits, ", ") print(str) -- Output: apple, banana, mango, orange
Tables in Lua are flexible and powerful, allowing you to create various data structures to suit your needs. Whether you need simple arrays, dictionaries, or complex nested structures, tables can handle it all.
For more detailed information, you can refer to the [Lua Documentation](https://www.lua.org/manual/5.4/manual.html#6).