Home / Lessons / Lesson 9
Intermediate Free

Tables & Arrays

In Luau, the Table is the only data structure. It is incredibly powerful and can act as an Array, a Dictionary, or an Object.


Arrays (Lists)

An array is an ordered list of items. You create a table using curly brackets {}. In Luau, arrays start at index 1 (unlike other languages that start at 0).

Working with Arrays
local weapons = {"Sword", "Bow", "Staff"}

print(weapons[1]) -- Prints "Sword"

-- Adding a new item to the end of the array
table.insert(weapons, "Dagger")

-- Removing the item at index 2 ("Bow")
table.remove(weapons, 2)

Dictionaries (Key-Value)

If you don't want a numbered list, you can use strings as the "index". This turns the table into a Dictionary, where every piece of data has a specific name (Key).

Player Data Dictionary
local playerData = {
    Name = "ekian",
    Level = 50,
    IsAdmin = true
}

print(playerData.Name) -- Prints "ekian"

-- Updating a value
playerData.Level += 1

Looping through Tables

To run code for every single item inside a table, we use a for loop. There are two standard ways to do this in Luau.

  • ipairs: Used for Arrays. It loops in exact numerical order (1, 2, 3...) and stops if it hits a gap.
  • pairs: Used for Dictionaries. It loops through string keys, but the order is not guaranteed.
Iterating with ipairs
local players = {"ekian", "builderman", "shedletsky"}

for index, name in ipairs(players) do
    print("Player #" .. index .. " is " .. name)
end