Is there any reason why one would use next over pairs()?

Hello. I have a very simple question. Is there any real reason why you would use next over pairs()?

for index, value in pairs(x) do
   -- code
end

-- or

for index, value in next, x do
     -- code
end

I don’t see any reason why one would be better, but if there is, I would be happy to know.

For vanilla Lua, people use next over pairs to avoid the __pairs metamethod. (For Lua 5.2 and over)

local example0 = { a = 1, b = 2, c = 3 };
local example1 = setmetatable({ d = 4, e = 5, f = 6 }, {
	__pairs = function()
		return pairs(example0);
	end;
});
for k, v in pairs(example1) do
	print(k, v);
end;
for k, v in next, example1 do
	print(k, v);
end;

prints out

-- pairs, these could be in any order
a	1
c	3
b	2
-- next, these could be in any order
e	5
d	4
f	6

As for Roblox Lua, the behaviour is the same, but apparently pairs doesn’t just return next.
Also next() doesn’t return iterators as opposed to pairs.

print(next({'a', 'b', 'c', 'd'}, 2)) --> c

For Lua 5.2 and over (doesn’t apply to Roblox), use next to avoid the __pairs metamethod, otherwise there’s no real reason to use one over another.

4 Likes

Crazyman32 wrote a good article on this.

That article is outdated. A lot has happened since then. Roblox engineers have rewritten the Lua VM (“Luau”) and done lots of optimizations.

1 Like