Tutorial · Scripting foundations

Luau tables and loops in Roblox: a beginner's guide

Almost every Roblox script uses tables. Players:GetPlayers() gives you one, an inventory is one, a list of checkpoints is one, and a ModuleScript usually returns one. Tables and loops go together: you make a table to hold many things, and a loop to do something with each of them. This guide covers both from the start, with examples from real games, and ends with the mistakes that cause most "attempt to index nil" and "attempt to iterate" errors.

Updated 14 November 20267 min readBeginnerLuauWritten by

In short

A Luau table holds many values in one variable. An array is a list in order, numbered from 1: {"Sword", "Shield"}. A dictionary stores values under names: {Coins = 50, Level = 3}. Loop over either with for key, value in myTable do. For arrays you can also use ipairs, which goes in order and stops at the first gap, and pairs for anything, in no promised order.

  • #list counts an array's items. It does not count a dictionary's keys; it gives 0 for {Coins = 50}.
  • Add to an array with table.insert(list, value) and remove with table.remove(list, index). Remove a dictionary key with dict.key = nil.
  • Tables are passed by reference: local b = a does not copy, both names point at the same table. Use table.clone(a) for a copy.
On this page
  1. Arrays
  2. Dictionaries
  3. Basic loops
  4. Looping tables
  5. Real examples
  6. Mistakes
  7. Quick reference
  8. Common errors
  9. With RoCode
  10. Questions
  11. Sources

Arrays: lists in order

An array is a list. Each item has a number, its index, starting at 1 (not 0, as in some other languages).

Script in ServerScriptService named ArrayBasics
-- Script in ServerScriptService named ArrayBasics. Press Play and read the Output.
local weapons: { string } = { "Sword", "Bow", "Staff" }

print(weapons[1]) --> Sword
print(weapons[3]) --> Staff
print(weapons[4]) --> nil: there is no fourth item
print(#weapons) --> 3: the # operator counts the items

-- Add to the end
table.insert(weapons, "Axe")
-- Add at a position: everything after it moves up one
table.insert(weapons, 1, "Fists")
print(table.concat(weapons, ", ")) --> Fists, Sword, Bow, Staff, Axe

-- Remove by position: everything after it moves down one
local removed = table.remove(weapons, 2)
print("Removed", removed) --> Removed Sword

-- Find the position of a value (nil if it is not there)
local index = table.find(weapons, "Bow")
print("Bow is at", index) --> Bow is at 2

-- Change an item
weapons[1] = "Gloves"
print(table.concat(weapons, ", ")) --> Gloves, Bow, Staff, Axe

{ string } after the name is a type: it says this is an array of strings, so the type checker warns you if you put a number in by mistake. It is optional, but it catches real bugs.

Roblox hands you arrays all the time: Players:GetPlayers(), folder:GetChildren(), CollectionService:GetTagged("Coin") and workspace:GetPartBoundsInBox(...) all return arrays.

Dictionaries: values with names

A dictionary stores each value under a key instead of a number. Keys are usually strings, but they can be almost anything, including a Player.

Script in ServerScriptService named DictionaryBasics
-- Script in ServerScriptService named DictionaryBasics.
local stats: { [string]: number? } = {
	Coins = 50,
	Gems = 2,
	Level = 1,
}

print(stats.Coins) --> 50
print(stats["Gems"]) --> 2: the same as stats.Gems
local key = "Level"
print(stats[key]) --> 1: square brackets let you use a variable as the key

-- Change a key, or add a new one
stats.Coins = 75
stats.Wins = 0

-- Remove a key by setting it to nil
stats.Gems = nil
print(stats.Gems) --> nil

-- # does not count dictionary keys (it would give 0 here), so count them with a loop
local count = 0
for _ in stats do
	count += 1
end
print("Keys:", count) --> Keys: 3

{ [string]: number } is the type of a dictionary whose keys are strings and whose values are numbers. The ? in number? above means a value may also be nil, which this example needs because it removes a key. Luau's type checker also warns when you use # on a table with string keys, because it is almost always a bug. A dictionary keyed by Player is very common on the server, for things like cooldowns: local lastHit: { [Player]: number } = {}. When a player leaves, set their key to nil so the table does not keep growing.

Array or dictionary?
ArrayDictionary
Looks like{ "a", "b", "c" }{ Coins = 50, Level = 3 }
Keys1, 2, 3 ... in orderNames (or any value)
#t worksYesNo, gives 0
Has an orderYesNo
Addtable.insert(t, v)t.key = v
Removetable.remove(t, i)t.key = nil
Good forLists: players, items in a queue, checkpointsLookups: stats, settings, data per player

Loops: numeric for, while and repeat

Luau has three loops that do not need a table at all.

Script in ServerScriptService named LoopBasics
-- Script in ServerScriptService named LoopBasics.
-- Numeric for: start, stop, and an optional step
for i = 1, 5 do
	print("Countdown step", i)
end
for i = 10, 0, -2 do
	print(i) --> 10, 8, 6, 4, 2, 0
end

-- while: repeats as long as the condition is true. Checks before each run.
local health = 100
while health > 0 do
	health -= 30
end
print("Health ended at", health) --> -20

-- repeat ... until: runs at least once, checks after each run
local tries = 0
repeat
	tries += 1
until tries >= 3
print("Tried", tries, "times")

-- break leaves a loop early; continue skips to the next round
for i = 1, 10 do
	if i % 2 == 0 then
		continue -- skip even numbers
	end
	if i > 7 then
		break -- stop completely
	end
	print("Odd:", i) --> 1, 3, 5, 7
end

Looping over tables: for k, v in t, ipairs and pairs

To do something with every item in a table, Luau gives you three ways. Modern Roblox code mostly uses the first.

Script in ServerScriptService named TableLoops
-- Script in ServerScriptService named TableLoops.
local fruits = { "Apple", "Banana", "Cherry" }
local prices: { [string]: number } = { Apple = 5, Banana = 3, Cherry = 8 }

-- 1. Generalized iteration: works on arrays and dictionaries
for index, fruit in fruits do
	print(index, fruit) --> 1 Apple, 2 Banana, 3 Cherry
end
for name, price in prices do
	print(name, "costs", price) -- order is not promised for dictionaries
end

-- 2. ipairs: arrays only, in order from 1, stops at the first nil
for index, fruit in ipairs(fruits) do
	print(index, fruit)
end

-- 3. pairs: any table, every key, in no promised order
for name, price in pairs(prices) do
	print(name, price)
end

-- Use _ for a value you do not need
for _, fruit in fruits do
	print("I like", fruit)
end
Which loop to use
LoopWorks onOrderStops at a nil gap
for k, v in t doArrays and dictionariesArrays in order from 1; dictionaries in no set orderNo
for i, v in ipairs(t) doArraysIn order from 1Yes
for k, v in pairs(t) doAnythingNo set orderNo
for i = 1, #t doArraysAny order you choose, even backwardsUses #t

You will see all three in tutorials, because generalized iteration (for k, v in t do) was added to Luau later. They all work. The guides on this site use the plain form because it is shorter and works on both kinds of table.

Tables and loops in real Roblox code

Here is the same pattern in three places you will meet in almost every game.

Script in ServerScriptService named RealLoops
-- Script in ServerScriptService named RealLoops.
local Players = game:GetService("Players")

-- 1. Every player in the server: heal them all
for _, player in Players:GetPlayers() do
	local character = player.Character
	local humanoid = character and character:FindFirstChildOfClass("Humanoid")
	if humanoid then
		humanoid.Health = humanoid.MaxHealth
	end
end

-- 2. Every child of a folder: make each part in a "Lava" folder glow
local lavaFolder = workspace:FindFirstChild("Lava")
if lavaFolder then
	for _, child in lavaFolder:GetChildren() do
		if child:IsA("BasePart") then
			child.Material = Enum.Material.Neon
		end
	end
end

-- 3. A list of tables: a shop catalog, sorted by price
type Item = { name: string, price: number }
local catalog: { Item } = {
	{ name = "Speed Coil", price = 300 },
	{ name = "Sword", price = 150 },
	{ name = "Jetpack", price = 900 },
}
table.sort(catalog, function(a: Item, b: Item): boolean
	return a.price < b.price -- true when a should come before b
end)
for position, item in catalog do
	print(position, item.name, item.price) --> 1 Sword 150, 2 Speed Coil 300, 3 Jetpack 900
end

The catalog is a nested table: an array whose items are dictionaries. That shape, a list of records, is how most games store items, quests and levels. table.sort takes a function that answers "should a come before b?" and puts the array in that order. Sorting a dictionary is not possible, because it has no order; copy what you need into an array first, as the next example does.

Script in ServerScriptService named TopScores
-- Script in ServerScriptService named TopScores. Sorts a dictionary by copying it into an array.
local coins: { [string]: number } = { Ana = 120, Ben = 340, Chloe = 90, Dev = 340 }

type Entry = { name: string, score: number }
local ranking: { Entry } = {}
for name, score in coins do
	table.insert(ranking, { name = name, score = score })
end

table.sort(ranking, function(a: Entry, b: Entry): boolean
	if a.score ~= b.score then
		return a.score > b.score -- highest first
	end
	return a.name < b.name -- same score: alphabetical, so the order is always the same
end)

for place, entry in ranking do
	print(place, entry.name, entry.score)
end
--> 1 Ben 340, 2 Dev 340, 3 Ana 120, 4 Chloe 90

This is how leaderboards work: per-player data lives in a dictionary, and when you need a top 10 you copy it into an array and sort. The leaderboard guide builds the full version.

Common table and loop mistakes

Removing items while looping forward

When you remove item 2, item 3 moves down into slot 2, and a forward loop jumps straight to slot 3, so it skips one. Loop backwards when you remove:

Script in ServerScriptService named RemoveWhileLooping
-- Script in ServerScriptService named RemoveWhileLooping.
local enemies: { string } = { "Zombie", "Ghost", "Ghost", "Zombie", "Ghost" }

-- Wrong: a forward loop that removes skips the item after each removal.
-- Right: go from the end to the start, so removing never moves an item you have not checked yet.
for i = #enemies, 1, -1 do
	if enemies[i] == "Ghost" then
		table.remove(enemies, i)
	end
end
print(table.concat(enemies, ", ")) --> Zombie, Zombie

For dictionaries, setting an existing key to nil while looping over it with pairs or for k, v in t is fine. Adding new keys during the loop is not: collect them in a second table and add them after.

Holes in arrays

Setting an array item to nil, as in list[2] = nil, leaves a hole. ipairs stops at the hole and #list may give a surprising number. Use table.remove(list, 2) instead, which closes the gap.

Tables are references, not copies

Script in ServerScriptService named TableReferences
-- Script in ServerScriptService named TableReferences.
local original = { "Sword" }
local sameTable = original -- not a copy: two names for one table
table.insert(sameTable, "Shield")
print(#original) --> 2: original changed too

local copy = table.clone(original) -- a real (shallow) copy
table.insert(copy, "Bow")
print(#original, #copy) --> 2 3

-- == compares whether two names point at the same table, not what is inside
print(original == sameTable) --> true
print(original == copy) --> false, even though they started with the same items

table.clone is shallow: a table inside the table is still shared. This matters with default player data. If every new player gets the same DEFAULT_DATA table, all players share one inventory. Clone it for each player (and clone the inner tables too).

Looping over something that is nil

for _, item in nil do fails with attempt to iterate over a nil value. It usually means a FindFirstChild found nothing or a dictionary key was misspelt. Check the value before the loop, as the Lava folder example does with if lavaFolder then. Reading a field of a missing item gives attempt to index nil with.

Using # on a dictionary

#stats is 0 for { Coins = 50 }, so if #stats == 0 then wrongly thinks it is empty. To check whether any key exists, use next(stats) == nil, which is true only for an empty table.

Table functions at a glance

The table library
FunctionWhat it does
table.insert(t, v)Adds v to the end of the array.
table.insert(t, i, v)Adds v at position i and moves the rest up.
table.remove(t, i)Removes and returns the item at i, moving the rest down. Without i, removes the last item.
table.find(t, v)The index of the first v in the array, or nil.
table.sort(t, f)Sorts the array in place. f(a, b) returns true when a goes first.
table.concat(t, sep)Joins an array of strings or numbers into one string.
table.clone(t)A shallow copy of the table.
table.clear(t)Removes every key but keeps the same table, so other references see it empty.
next(t) == nilTrue when the table has no keys at all.

Common errors and fixes

These are the errors tables and loops cause most often.

attempt to iterate over a nil value

The table you loop over does not exist. Print it before the loop, and check FindFirstChild results. See the full fix.

attempt to index nil with ...

You read a field of an item that is not there, such as items[5].name when there are 4 items. See attempt to index nil with.

Expected 'do' when parsing loop

A for or while line is missing its do. See Expected do when parsing loop.

Expected ',' after table constructor element

A comma is missing between two items inside { }. See the fix.

My loop skips items

You remove items while looping forward. Loop backwards with for i = #t, 1, -1 do.

Build it with RoCode

If you would rather not set this up by hand, RoCode can build it in the place you have open. RoCode is an independent AI agent for Roblox Studio, not made by Roblox: you describe the change in a web chat, and its Studio plugin creates the parts and scripts in your Explorer, so there is no code to paste.

You type

Read my shop script and explain how its item table and loops work, then change it so the items are sorted by price and sold-out items are removed safely.

RoCode does
  • Can read your scripts first, so it works with the tables you already have
  • Writes the scripts with Create Script and is told to compile-check each one with Check Script
  • Sets an undo point before and after each batch of changes, so Ctrl+Z steps back one batch at a time

How RoCode connects to Studio.

Questions

What is a table in Luau?

The one data structure Luau has: a value that holds many other values. Used as a list it is an array; used with named keys it is a dictionary.

What is the difference between pairs and ipairs?

ipairs goes through an array in order from 1 and stops at the first nil. pairs goes through every key of any table, in no promised order.

Do I still need pairs and ipairs in Roblox?

No. Luau's generalized iteration, for key, value in t do, works on arrays and dictionaries. ipairs is still useful when you want a loop to stop at the first gap.

How do I get the length of a table?

Use #t for arrays. For dictionaries, count with a loop, because # does not count named keys.

How do I remove something from a table while looping?

For arrays, loop backwards (for i = #t, 1, -1 do) and use table.remove. For dictionaries, setting the current key to nil during the loop is fine.

Why does changing one table change another?

Both variables point at the same table. Make a separate copy with table.clone.

Sources and further reading

How the code was checked: every script on this page passes Luau's strict type checker against Roblox's API definitions (luau-lsp, 14 November 2026). A type check catches misspelt APIs and wrong types, not game logic, so playtest in Studio before you publish.

Try RoCode on your own place.

Free every day, no card required. Install the plugin, describe the feature, and review what lands in Studio.