Understand Lua tables, the most powerful data structure in Lua.
Tables are the only data structure in Lua, but they can be used as arrays, dictionaries, or objects!
-- Array (indexed by numbers)
local fruits = {"Apple", "Banana", "Cherry"}
print(fruits[1]) -- Apple (Lua starts at 1!)
print(fruits[2]) -- Banana
print(fruits[3]) -- Cherry
Arrays in Lua start at index 1, not 0 like many other languages!
-- Dictionary (key-value pairs)
local player = {
name = "Steve",
level = 10,
health = 100,
isAlive = true
}
print(player.name) -- Steve
print(player["level"]) -- 10
Access values using dot notation or bracket notation.
Learn how to add, remove, and modify table elements.
local inventory = {"Sword", "Shield"}
-- Add to end
table.insert(inventory, "Potion")
-- Add at specific index
table.insert(inventory, 2, "Helmet")
print(inventory[1]) -- Sword
print(inventory[2]) -- Helmet
print(inventory[3]) -- Shield
print(inventory[4]) -- Potion
table.insert() adds elements to arrays.
local items = {"A", "B", "C", "D"}
-- Remove last element
table.remove(items)
-- Remove at index
table.remove(items, 1)
-- Result: {"B", "C"}
table.remove() removes elements from arrays.
local numbers = {10, 20, 30, 40}
print(#numbers) -- 4
for i = 1, #numbers do
print(numbers[i])
end
Use # to get the length of an array-style table.
Different ways to loop through table elements.
local players = {"Alice", "Bob", "Charlie"}
for index, name in ipairs(players) do
print(index .. ": " .. name)
end
ipairs() iterates through arrays in order.
local stats = {
strength = 10,
intelligence = 15,
dexterity = 8
}
for key, value in pairs(stats) do
print(key .. ": " .. value)
end
pairs() iterates through all key-value pairs (order not guaranteed).
Create an inventory table and add/remove items.
local inventory = {}
-- Add 3 items to inventory
-- Print all items
for i, item in ipairs(inventory) do
print(i .. ": " .. item)
end
local inventory = {}
table.insert(inventory, "Sword")
table.insert(inventory, "Potion")
table.insert(inventory, "Shield")
for i, item in ipairs(inventory) do
print(i .. ": " .. item)
end
Create a player stats table and print each stat.
-- Create player table with name, level, health, and mana
-- Print all stats
for stat, value in pairs(player) do
print(stat .. ": " .. value)
end
local player = {
name = "Hero",
level = 15,
health = 100,
mana = 50
}
for stat, value in pairs(player) do
print(stat .. ": " .. value)
end
Continue your learning journey