Table Library in Lua
Lua provides a powerful table library with built-in functions for manipulating tables efficiently. These functions handle common operations like inserting, removing, sorting, and joining table elements. Mastering the table library will make your code cleaner and more efficient. Let's explore all the essential table functions!
table.insert()
Insert elements into a table:
local fruits = {"apple", "banana"}
-- Insert at end
table.insert(fruits, "cherry")
-- fruits = {"apple", "banana", "cherry"}
-- Insert at specific position
table.insert(fruits, 2, "blueberry")
-- fruits = {"apple", "blueberry", "banana", "cherry"}
table.insert(t, value)- Append to endtable.insert(t, pos, value)- Insert at position
Click Run to execute your code
table.remove()
Remove elements from a table:
local fruits = {"apple", "banana", "cherry", "date"}
-- Remove last element
local removed = table.remove(fruits)
print(removed) -- "date"
-- fruits = {"apple", "banana", "cherry"}
-- Remove at specific position
local removed = table.remove(fruits, 2)
print(removed) -- "banana"
-- fruits = {"apple", "cherry"}
table.remove() shifts elements to fill
the
gap. Removing from the beginning or middle is O(n) complexity!
Click Run to execute your code
table.sort()
Sort table elements in-place:
local numbers = {5, 2, 8, 1, 9, 3}
-- Sort ascending (default)
table.sort(numbers)
-- numbers = {1, 2, 3, 5, 8, 9}
-- Sort descending with custom comparator
table.sort(numbers, function(a, b)
return a > b
end)
-- numbers = {9, 8, 5, 3, 2, 1}
-- Sort strings
local names = {"Charlie", "Alice", "Bob"}
table.sort(names)
-- names = {"Alice", "Bob", "Charlie"}
Custom Sorting
local people = {
{name = "Alice", age = 25},
{name = "Bob", age = 30},
{name = "Charlie", age = 20}
}
-- Sort by age
table.sort(people, function(a, b)
return a.age < b.age
end)
-- Charlie (20), Alice (25), Bob (30)
Click Run to execute your code
table.concat()
Join table elements into a string:
local words = {"Hello", "World", "Lua"}
-- Join with default separator (empty string)
local result = table.concat(words)
print(result) -- "HelloWorldLua"
-- Join with custom separator
local result = table.concat(words, " ")
print(result) -- "Hello World Lua"
-- Join with separator and range
local result = table.concat(words, ", ", 1, 2)
print(result) -- "Hello, World"
table.concat() instead of
string
concatenation in loopsβit's much faster for building long strings!
Click Run to execute your code
table.pack() and table.unpack()
table.pack() - Lua 5.2+
Pack values into a table:
local packed = table.pack(10, 20, 30)
-- packed = {10, 20, 30, n = 3}
-- 'n' field stores the count
print(packed[1]) -- 10
print(packed.n) -- 3
table.unpack() (or unpack in Lua 5.1)
Unpack table into multiple values:
local numbers = {10, 20, 30}
-- Unpack all values
local a, b, c = table.unpack(numbers)
print(a, b, c) -- 10 20 30
-- Unpack range
local x, y = table.unpack(numbers, 1, 2)
print(x, y) -- 10 20
-- Use in function calls
local function add(a, b, c)
return a + b + c
end
print(add(table.unpack(numbers))) -- 60
Click Run to execute your code
Practical Examples
Building a CSV String
local function toCSV(rows)
local lines = {}
for i, row in ipairs(rows) do
table.insert(lines, table.concat(row, ","))
end
return table.concat(lines, "\n")
end
local data = {
{"Name", "Age", "City"},
{"Alice", "25", "NYC"},
{"Bob", "30", "LA"}
}
print(toCSV(data))
Stack Implementation
local Stack = {}
function Stack:new()
local stack = {items = {}}
setmetatable(stack, {__index = self})
return stack
end
function Stack:push(value)
table.insert(self.items, value)
end
function Stack:pop()
return table.remove(self.items)
end
function Stack:peek()
return self.items[#self.items]
end
function Stack:isEmpty()
return #self.items == 0
end
local s = Stack:new()
s:push(10)
s:push(20)
print(s:pop()) -- 20
Queue Implementation
local Queue = {}
function Queue:new()
local queue = {items = {}}
setmetatable(queue, {__index = self})
return queue
end
function Queue:enqueue(value)
table.insert(self.items, value)
end
function Queue:dequeue()
return table.remove(self.items, 1)
end
local q = Queue:new()
q:enqueue("first")
q:enqueue("second")
print(q:dequeue()) -- "first"
Click Run to execute your code
Quick Reference
| Function | Purpose | Example |
|---|---|---|
table.insert(t, v) |
Append value | table.insert(arr, 10) |
table.insert(t, i, v) |
Insert at position | table.insert(arr, 2, 10) |
table.remove(t) |
Remove last | table.remove(arr) |
table.remove(t, i) |
Remove at position | table.remove(arr, 2) |
table.sort(t) |
Sort ascending | table.sort(arr) |
table.sort(t, comp) |
Sort with comparator | table.sort(arr, function(a,b) return a>b end) |
table.concat(t, sep) |
Join to string | table.concat(arr, ", ") |
table.unpack(t) |
Unpack values | a, b = table.unpack(arr) |
Practice Exercise
Try these table library challenges:
Click Run to execute your code
Summary
In this lesson, you learned:
table.insert()for adding elementstable.remove()for removing elementstable.sort()for sorting with custom comparatorstable.concat()for efficient string buildingtable.pack()andtable.unpack()for value manipulation- Practical implementations: CSV, Stack, Queue
What's Next?
You've mastered the table library! Next, we'll explore metatablesβone of Lua's most powerful features. Metatables let you customize table behavior, overload operators, and create sophisticated object-oriented patterns. Let's continue! π
Enjoying these tutorials?