Differences when looping through a loop with ipairs()

Hello! I was wondering what the difference between running the following code samples:
for _, output in {"obj1", "obj2"} do print(output) end
for _, output in ipairs({"obj1", "obj2"}) do print(output) end
The second function uses ipairs(), while the first one does not.

Thanks!

The first option is typical for Luau and doesn’t exist in native implementations or LuaJIT. It’s generalized iteration so we don’t have to use ipairs or pairs (or next and other iterators).

In case of a normal sequential array, e.g. {"a", "b", "c"} that contains no “gaps” and whose indices are 1 (for a), 2 (for b), 3 (for c), they behave exactly the same. FIrst value will be a, then b, and so forth.

local t = {
	[1] = "a";
	[2] = "b";
	[5] = "d";
	[6] = "e";
	[3] = "c";
}
for i,v in ipairs(t) do
	print(i, v)
end
for i,v in t do
	print(i, v)
end

The array above has “gaps” (missing 4). ipairs is going to print 1, 2, and 3, then stop, while the generalized iterator is going to continue with 5 and 6 too.

If the table was mixed, it would print all string keys too, but order should be unspecified, as when using pairs.

EDIT.

More information.

RFC on generalized iteration

Lua Recap in May 2022

Dk how accurate this info is but I do remember reading some benchmarks which showed that generalized iteration was faster than pairs and pairs (small margin tho) but ye I never benchmarked it myself

1 Like

Interesting. At first glance I’d expect generic for loop to be the fastest, ipairs slightly faster than pairs and generalized iterator extremely close behind, but I guess it depends on the implementation, since we know Roblox improved the execution time of ipairs over for i=1, #t do.

I don’t have enough time to make a proper benchmark, but after a quickly thrown together one I saw ipairs being .02 seconds behind on a table with 50 million elements. So at the end of the day it’s readability that matters the most. I like to still use ipairs() to signify an array.

Pretty sure you shouldn’t use ipairs or pairs anymore because removing them provides the same speed. And you don’t need to think critically on what you need to use.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.