We can omit all ipairs and pairs in for-loop

I’ve found that for the vast majority of for loops, we don’t need to differentiate between ipairs and pairs. This is weird and hard to differentiate for new developers, and I think it’s counter-intuitive and bad design. If we need to differentiate, we can decide whether the index is a number or a letter in the for loop.According to this Luau Recap: May 2022 new Luau update, can I delete all the ipairs and pairs in my for loop?

1 Like

You can. there may be issues for tables with non-sequential number keys, but these tables have a lot of problems either way.

Yes you can, just keep in mind that there’s a slight nuance with generalized iteration.

local t = {1, 2, 3, a = 1, b = 2, c = 3}
t[2] = nil

for i, v in pairs(t) do --Iterates over all key/value pairs.
	print(i, v)
end

--1 1
--3 3
--a 1
--b 2
--c 3

for i, v in ipairs(t) do --Iterates over all index/value pairs stopping at the first empty slot (nil value).
	print(i, v)
end

--1 1

for i, v in t do --Iterates over the array part (stopping at the first empty slot) and then iterates over the hash part.
	print(i, v)
end

--1 1
--a 1
--b 2
--c 3

Mixed tables (tables with array and hash parts) are discouraged and Roblox’s own API methods will only ever return pure arrays/pure hashes.

4 Likes

Thank you for your detailed reply! I got a lot of details that I didn’t notice!