Sequential Data via Tables
Lua does not implement a distinct array data type; instead, sequential data structures are represented using tables. These tables function as dynamic arrays that can automatically resize to accommodate new elements. Because Lua tables are flexible, they can store values of any type, including numbers, strings, booleans, or even other tables nested within the array.
Initialization and Indexing
Creating a sequential collection involves initializing a table with a comma-separated list of values. By convention, Lua uses 1-based indexing for these structures.
local inventory = {"potion", "sword", "shield", "map"}
-- Accessing the first item
print(inventory[1])
Elements can be modified directly by assigning a new value to a specific index.
-- Updating the second item
inventory[2] = "axe"
print(inventory[2]) -- Output: axe
Dynamic Resizing
The standard library provides the table module to handle modifications to the size of the array. The table.insert function allows you to append elements to the end of the sequence or insert them at a specific position.
-- Appending an item to the end
table.insert(inventory, "helmet")
-- Inserting at a specific index (e.g., index 2)
table.insert(inventory, 2, "bow")
To remove elements, table.remove shifts subsequent elements to close the gap. If no index is specified, it removes the last element.
-- Removing the item at index 1
table.remove(inventory, 1)
Iteration
Traversing a sequential table is commonly performed using a numeric for loop combined with the length operator #. This method is efficient for arrays because the length operator provides the size of the sequence.
for i = 1, #inventory do
print("Slot " .. i .. ": " .. inventory[i])
end
Alternatively, ipairs can be used to iterate over numeric indices from 1 until the first nil value is encountered, which ensures only sequential array parts are processed.
for index, value in ipairs(inventory) do
print(index, value)
end