Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

For loops: Should I use next or pairs?

Pairs or next?

I've been looking around on lua.org, at iterator functions, and came across something that caught my eye. According to the page, the "pairs" iterator is just a nested "next" function. Here's the code they provide:

function pairs(t)
	return next,t,nil
end

You can also find it here: http://www.lua.org/pil/7.3.html

But if this is the case, what's the point of it? Is pairs just the exact same as using next? In my understanding, the "pairs" function is the equivalent to saying something like this:

local function p(...)
	print(...)
end

Whereas I'm just using one function to call another, when I can just call that other function directly. Anyway, if anyone knows a bit more about this than me, or if there is a difference between pairs and next (besides how they're formatted in a for loop), I'd appreciate the insight. Thanks for reading.

1 comment

0

I swear this exact question has been asked before but I can't find it....

1 answer

✓ Accepted answer

Either
pairs is pretty much just a frontend for next, and actually uses next behind the scenes. Using next is marginally faster, but the difference is negligable.

At the end of the day, it all boils down to personal taste and clean code.

1 comment

0

Thank you for clarifying.

This discussion is preserved as it was. New answers, comments, and votes are closed.