Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Luau Scripting

Tables: Lists and Dictionaries in Luau

"Master Luau tables for Roblox: arrays and dictionaries, 1-based indexing, the table library, sorting, nested tables, references vs copies, clone and freeze."

The table is Luau's only data structure, and it does everything: lists, records, sets, queues, inventories, whole game configurations. If you learn one thing about data in Roblox, learn tables. Every shop, leaderboard and inventory you build will be a table.

Arrays (lists)

An array is a table whose items are stored under 1, 2, 3, and so on:

LUA
local fruits = {"apple", "banana", "cherry"}

print(fruits[1])        --> apple   (indexes start at 1!)
print(fruits[3])        --> cherry
print(#fruits)          --> 3       (the length operator)
print(fruits[4])        --> nil     (nothing there)

Add and remove items with the table library:

LUA
table.insert(fruits, "date")          -- add to the end
table.insert(fruits, 1, "apricot")    -- insert at position 1
table.remove(fruits)                  -- remove the last item
table.remove(fruits, 1)               -- remove the first, shifting the rest down

print(table.find(fruits, "banana"))   --> 2 (index) or nil if missing
print(table.concat(fruits, ", "))     --> apple, banana, cherry

Do not leave holes. If you set fruits[10] = "x" on a three-item array, #fruits becomes unreliable. Use table.insert and table.remove and keep arrays dense.

Dictionaries (key-value pairs)

A dictionary stores values under names called keys:

LUA
local player = {
	Name = "Mira",
	Level = 7,
	Coins = 120,
	IsMember = false,
}

print(player.Name)           --> Mira
print(player["Level"])       --> 7
player.Coins += 30           -- change a value
player.Title = "Explorer"    -- add a new key
player.IsMember = nil        -- remove a key (set to nil)

player.Name and player["Name"] mean the same. Use square brackets when the key is a variable or contains spaces: player[keyName]. The # operator does not count dictionary keys; it only works for arrays.

Table keys can be any value except nil, including instances and numbers, which makes powerful lookups possible:

LUA
local visited = {}
visited[workspace.Block] = true     -- a table keyed by an Instance

Looping over tables

LUA
for index, fruit in ipairs(fruits) do     -- arrays, in order
	print(index, fruit)
end

for key, value in pairs(player) do        -- dictionaries, no guaranteed order
	print(key, value)
end

ipairs stops at the first nil; pairs visits every key but in no particular order. If order matters, collect the keys in an array and sort them.

Sorting

table.sort sorts in place. Give it a comparison function for custom order:

LUA
local scores = {40, 5, 90, 12}
table.sort(scores)                              --> 5 12 40 90
table.sort(scores, function(a, b) return a > b end)  --> 90 40 12 5

A leaderboard is a sorted array of small tables:

LUA
local board = {
	{name = "Ana", score = 30},
	{name = "Ben", score = 55},
}
table.sort(board, function(a, b) return a.score > b.score end)
print(board[1].name)     --> Ben

The comparison function must be consistent (never return true for equal items) or table.sort may error with "invalid order function".

Nested tables

Tables can contain tables, which is how structured data like a shop catalogue is made:

LUA
local shop = {
	{name = "Wooden Sword", price = 50, tags = {"weapon", "starter"}},
	{name = "Shield", price = 80, tags = {"armor"}},
}

print(shop[1].name)           --> Wooden Sword
print(shop[1].tags[2])        --> starter
print(#shop, #shop[1].tags)   --> 2 2

References, copies and freezing

A table variable holds a reference. Assigning it to another variable does not copy the contents:

LUA
local a = {1, 2, 3}
local b = a
b[1] = 99
print(a[1])      --> 99   (a and b are the same table)

local c = table.clone(a)   -- a shallow copy
c[1] = 5
print(a[1])      --> 99   (a is untouched)

table.clone is shallow: nested tables are still shared. For a deep copy you write a recursive function.

To make a table read-only (good for constants), freeze it:

LUA
local Config = table.freeze({
	MaxPlayers = 12,
	RoundTime = 120,
})
Config.MaxPlayers = 20     -- error: attempt to modify a readonly table

Other helpers: table.unpack(t) returns the items as separate values, table.create(n, value) makes an array of n items, table.clear(t) empties a table, and table.move copies a range.

Tables as sets and counters

A set is a dictionary whose values are true:

LUA
local seen = {}
for _, id in {5, 8, 5, 3, 8} do
	seen[id] = true
end
-- membership test: if seen[5] then ...

A counter is a dictionary of numbers:

LUA
local counts = {}
for _, word in {"red", "blue", "red"} do
	counts[word] = (counts[word] or 0) + 1
end
print(counts.red, counts.blue)   --> 2 1

Stand-in: an array with 1-based indexes

Real Luau arrays start at 1. This JavaScript stand-in wraps an array so that get(1) is the first item, and implements insert, remove and find with Luau's rules. Edit it to try an insert in the middle.

JS Stand-in: Luau array rules (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Stand-in: references, clone and sort

JS Stand-in: references vs copies, leaderboard sort (JavaScript)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • Starting at index 0; arrays start at 1.
  • Using # on a dictionary; it returns 0 for non-array tables.
  • Changing an array while looping over it with ipairs; build a new array or loop backwards.
  • Forgetting that assignment shares the table; use table.clone.
  • Putting nil in the middle of an array.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the index of the first item of a Luau array?

    Luau arrays start at 1.
  2. 2. What does the # operator count?

    gives the length of an array or string. It does not count dictionary keys.

  3. 3. After local b = a (a is a table) and b[1] = 99, what is a[1]?

    Assigning a table copies the reference, not the contents.
  4. 4. How do you remove a key from a dictionary?

    Assigning nil to a key removes it from the table.

Summary

  • Arrays are 1-based tables; use table.insert, table.remove, table.find, table.concat and #.
  • Dictionaries map keys to values; set a key to nil to remove it.
  • Loop with ipairs (ordered arrays) or pairs (any table).
  • Tables are references; use table.clone for a shallow copy and table.freeze for constants.

Next: Modules, Types and Strict Mode