Whats the Difference Between Ipairs and pairs?

ipairs iterates through arrays, while pairs iterates through both arrays and dictionaries.

local array = {1, 2, 3, 4, 5}
local dictionary = {index = "value", key = 2}

-- This won't run because `dictionary` doesn't contain any numerical indices
for i, v in ipairs(dictionary) do
   print(i, v)
end

-- This will run because `array` is an array (table with numerical indices)
for i, v in ipairs(array) do
   print(i, v)
end

-- This will run because `pairs` covers both arrays and dictionaries
for i, v in pairs(dictionary) do
   print(i, v)
end

-- This will also run for the same reason as listed above
for i, v in pairs(array) do
   print(i, v)
end

However, you no longer need to use ipairs or pairs since generalized iteration was introduced.

-- These both behave and do the same thing

for i, v in dictionary do
   print(i, v)
end

for i, v in array do
   print(i, v)
end

Yes

18 Likes