invalid argument #1 to 'ipairs' (table expected, got nil)in Roblox Luau: what it means and how to fix it

What it means

A built-in function received the wrong type of value. The number is which argument was wrong, the name is the function, and the brackets say what it needed and what it got.

The same error also shows up as:

  • invalid argument #1 to 'pairs' (table expected, got nil)

The smallest script that triggers it

Triggers the errorline 2: error here
local inventory
for index, item in ipairs(inventory) do
  print(index, item)
end

The fix

Fixedline 1: the fix
local inventory = { "Sword", "Shield" }
for index, item in ipairs(inventory) do
  print(index, item)
end

ipairs needs a table to walk through. Giving the variable a table, even an empty one, makes the loop valid.

Common causes

  1. The table variable was never assigned, or was assigned in a branch that did not run.
  2. A function that should return a table returned nothing.
  3. Loaded data was nil for a new player and was looped over without a default such as `data or {}`.

Practice this until it sticks

A Deep Dive on tables and loops: 5-minute lessons, each with a quiz. What you miss comes back in the next module. One Deep Dive a day is free. No card.