Lesson 3 of 8
Tables
Lua has one data structure, the table, which works as an , a and an object. Learn to create tables and over them.
-- As an array (1-indexed!):
local fruits = { "apple", "banana", "cherry" }
print(fruits[1]) -- apple (NOT fruits[0])
print(#fruits) -- 3
table.insert(fruits, "date") -- append
table.insert(fruits, 1, "avocado") -- insert at front
table.remove(fruits, 2) -- remove by index
table.sort(fruits)
-- Iterate an array:
for i, fruit in ipairs(fruits) do
print(i, fruit)
end-- As a dictionary:
local student = {
name = "Ada",
age = 17,
grade = 95,
}
print(student.name) -- dot access
print(student["name"]) -- same thing
student.email = "ada@example.com" -- add a key
student.age = nil -- delete a key
-- Iterate a dictionary:
for key, value in pairs(student) do
print(key, value)
end
-- Nesting is free:
local party = {
members = {
{ name = "Ada", hp = 100 },
{ name = "Alan", hp = 85 },
},
gold = 250,
}
print(party.members[2].name) -- AlanFinished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.