Lua Tables & Data Structures

Learn about Lua tables for arrays, dictionaries, and objects

Tables in Lua

Tables are Lua's only data structure, yet they are incredibly versatile. They can be used as arrays, dictionaries, objects, and more.

Table Basics

Tables are created using curly braces:

table_basics.lua
-- Creating an empty table
local myTable = {}

-- Adding values
myTable[1] = "Hello"
myTable[2] = "World"

-- Accessing values
print(myTable[1]) -- Output: Hello
print(myTable[2]) -- Output: World

-- Tables with initial values
local fruits = {"Apple", "Banana", "Orange"}
print(fruits[1]) -- Output: Apple
print(fruits[3]) -- Output: Orange

Tables as Dictionaries

Tables can use any value (except nil) as a key, making them perfect for dictionaries:

table_dictionary.lua
-- Table as a dictionary
local player = {
  name = "Hero",
  health = 100,
  level = 5,
  inventory = {"Sword", "Shield", "Potion"}
}

-- Accessing values
print("Player: " .. player.name)
print("Health: " .. player.health)
print("Level: " .. player.level)

-- Alternative access syntax
print("Player: " .. player["name"])

-- Nested tables
print("First item: " .. player.inventory[1])

Table Iteration

You can iterate through tables using various methods:

table_iteration.lua
-- Numeric iteration with ipairs
local colors = {"Red", "Green", "Blue"}

print("Colors (ipairs):")
for i, color in ipairs(colors) do
  print(i .. ": " .. color)
end

-- Dictionary iteration with pairs
local person = {
  name = "Alice",
  age = 25,
  job = "Developer"
}

print("\nPerson details (pairs):")
for key, value in pairs(person) do
  print(key .. ": " .. value)
end