Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

For loops: Should I use next or pairs?

Asked by 8 years ago

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.

0
I swear this exact question has been asked before but I can't find it.... BlueTaslem 18071 — 8y

1 answer

Log in to vote
2
Answered by 8 years ago

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.

0
Thank you for clarifying. CodingEvolution 490 — 8y
Ad

Answer this question