This tutorial provides a detailed introduction to data structures in Lua, with a focus on Lua’s unique data structure—Tables—and its various uses.
1. Tables – The only data structure in Lua
Tables in Lua are a powerful data structure that can be used to represent various data formats such as arrays, dictionaries, and sets.
1.1 Arrays (indexed tables)
Arrays in Lua are implemented using tables, with indices starting from 1.
-- Creation of arrays
local fruits = {"apple", "banana", "orange", "grape"}
-- Accessing array elements (index starting from 1)
print("First fruit:", fruits[1])
print("Last fruit:", fruits[4])
-- Get array length
print("Number of fruits:", #fruits)
-- Traverse array (Method 1)
print("\nTraverse array:")
for i = 1, #fruits do
print("index ", i, ": ", fruits[i])
end
-- Traverse array (Method 2)
print("\nTraverse using ipairs:")
for index, value in ipairs(fruits) do
print("index ", index, ": ", value)
end
1.2 Dictionary (key-value pair table)
Dictionaries store data using key-value pairs.
-- Creation of Dictionary
local person = {
name = "boy",
age = 30,
job = "Engineer",
married = true
}
-- Accessing dictionary elements
print("name:", person.name)
print("age:", person["age"])
-- Modify dictionary elements
person.age = 31
print("Modified age:", person.age)
-- Add new elements
person.city = "New York"
print("New City:", person.city)
-- Delete element (set to nil)
person.married = nil
print("deleted marital status:", person.married) -- output nil
-- Traverse the dictionary
print("\nTraverse dictionary:")
for key, value in pairs(person) do
print("key:", key, "value:", value)
end
1.3 Hybrid Tables (containing both array and dictionary components)
Lua tables can contain both array and dictionary parts.
-- Creation of Mixed Tables
local mixed = {
Element 1 "," Element 2 ", -- Array section
name = "Mixed Table", -- Dictionary section
id = 1001
}
print("\nTraverse mixed table:")
for key, value in pairs(mixed) do
print("key:", key, "value:", value)
end
1.4 Nested Tables
Tables can be nested to create complex data structures.
-- Creation of nested tables
local students = {
{name = "boy", age = 20, scores = {math = 85, history = 90}},
{name = "girl", age = 22, scores = {math = 92, english = 88}}
}
print("First student's score:", students[1].scores.english)
print("Second student's score:", students[2].scores.math)
2. Metatables
Metatables allow us to modify the behavior of a table and define special operations for it.
-- Create a table
local t1 = {10, 20}
local t2 = {30, 40}
-- Create Meta Table
local mt = {
-- __add meta method: Define addition operation
__add = function(a, b)
local result = {}
for i, v in ipairs(a) do
result[i] = v
end
for i, v in ipairs(b) do
result[#result + 1] = v
end
return result
end,
-- __tostring meta method: defining the behavior when printing a table
__tostring = function(t)
local str = "{ "
for i, v in ipairs(t) do
str = str .. v
if i < #t then
str = str .. ", "
end
end
str = str .. " }"
return str
end
}
-- Set Meta Table
setmetatable(t1, mt)
setmetatable(t2, mt)
-- Using meta methods
local t3 = t1 + t2 -- Call the __add meta method
print("t1:", tostring(t1))
print("t2:", tostring(t2))
print("t1 + t2:", tostring(t3))
3. The use of tables as different data structures
3.1 Tables used as sets
Tables can be used to implement the functionality of sets.
-- Create a collection (using keys to store elements, with a value of true)
local set = {}
-- Add elements
set["apple"] = true
set["banana"] = true
set["orange"] = true
-- -Check if the element exists
print("apple in collection:", set["apple"] ~= nil)
print("grape in collection:", set["grape"] ~= nil)
-- Delete element
set["banana"] = nil
print("Delete banana in collection:", set["banana"] ~= nil)
-- Traverse the set
print("\nElements in collection:")
for element in pairs(set) do
print(element)
end
3.2 Tables used as stacks
Tables can be used to implement the functionality of stacks.
local stack = {}
-- Stack in
function push(item)
table.insert(stack, item)
end
-- Out of Stack
function pop()
return table.remove(stack)
end
-- Test stack operation
push("A")
push("B")
push("C")
print("Top stack elemen:", pop())
print("Top stack elemen:", pop())
print("Top stack elemen:", pop())
3.3 Tables used as queues
Tables can also be used to implement queue functionality.
local queue = {}
-- Join the queue
function enqueue(item)
table.insert(queue, item)
end
-- Get out of the queue
function dequeue()
return table.remove(queue, 1)
end
-- Test queue operation
enqueue(1)
enqueue(2)
enqueue(3)
print("First element:", dequeue())
print("First element:", dequeue())
print("First element:", dequeue())
4. Common table operations
Lua provides some built-in functions for manipulating tables.
local testTable = {5, 2, 8, 1, 9}
-- Sort
table.sort(testTable)
print("\nsorted table:")
for i, v in ipairs(testTable) do
print(v)
end
-- Insert element
table.insert(testTable, 3, 10) -- Insert 10 at index 3
print("\nTable after inserting element:")
for i, v in ipairs(testTable) do
print(v)
end
-- Delete element
table.remove(testTable, 2) -- Delete the element at index 2
print("\nTable after removing elements:")
for i, v in ipairs(testTable) do
print(v)
end
Summarize
- Tables in Lua are a flexible data structure that can represent various data formats.
- Tables can be used as arrays, dictionaries, mixed tables, and nested tables.
- Metatables allow us to modify the behavior of tables and implement features such as operator overloading.
- Tables can simulate common data structures such as sets, stacks, and queues.
- Lua provides a rich set of table manipulation functions, such as sorting, insertion, and deletion.