Is there any difference looping with pairs() and without pairs()?

Hello!!
So here is example:

local test = {"1", "2", "3"}

for i, number in test do
	print("without pairs()",number)
end

for i, number in pairs(test) do
	print("with pairs()",number)
end

They print exactly the same, and work same.
Is there any difference with pairs() and without it?

Yes there is a difference. As a preface, iterating over a table without pairs (or any iterator function for that matter) in Luau is called generalized iteration and implements an __iter metamethod which can be invoked when iterating over a table without an iterator function for custom iteration behaviour.

With that aside, pairs does not guarantee numeric order and is generally slow at iterating over a numeric-indexed table compared to ipairs (which is faster in Luau than vanilla Lua) and generalized iteration.

Default behaviour for generalized iteration does guarantee numeric order and has a similar speed to ipairs. It also allows you to iterate over non-numeric index/missing index dictionaries, so you do not have to make the conscious decision of choosing what iterator to use (between pairs, ipairs [and next if you’re using that]).

In your case though, you will get the same behaviour because although pairs doesn’t guarantee order of iteration, it does do a good job at doing it even if it isn’t what it’s meant for with respect to non-missing numerical-indexed tables.

There’s an article on it here:

But if you’re interested in the specifics (implementation, performance and such), the RFC is here:

4 Likes

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