What is next used for?

In scripts, I have seen stuff like this:

for i,v in next(whatever) do -- idk if this is how u use it but yeah
-- The code to run
end

I have a few questions.

  • What is it?
  • How is it different from pairs/ipairs
  • Why do you use it
  • When should you use it

I think this topic answers your question: Differences between pairs and next?

RTFM: Lua Globals / PiL 7.3 - Stateless Iterators / Search forum (see thread linked in above post)

Besides that though, next can make for some interesting use cases such as checking if a table is truly empty. Consider the following:

local function isEmpty(t)
    return next(t) == nil
end

But Colbert, why not #t == 0, isn’t what you’re doing redundant? The len operator only works for arrays so if you have a dictionary (including if indexed by numbers if non-contiguous) len will return 0 but it’s not actually empty. Rare case you’ll need it but it may come up some time.

For generic for iteration there’s generally no case where you need or want next because it’s not clear what you’re iterating over to either yourself or fellow developers and you want to stay consistent when using offered generic iterators. ipairs for arrays, pairs for dictionaries and a custom iterator if you have that one esoteric case where neither ipairs or pairs work (i.e. for priority, name, handler in handlers:GetIterator() do).

5 Likes

https://www.lua.org/pil/7.3.html

Check out both sections on the “next” global function.

1 Like

This is what pairs() uses to determine if it has reached the end of a dictionary.

Moreover the pairs() iterator is essentially built off the back of next.

Correct me if I am wrong, but there is no difference between pairs() and next(),
but I prefer to use the latter (I think it makes the code look more organized) and I don’t know why lol.

for i, v in next(table) do

for i, v in pairs(table) do