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

What are the advantages of using "next"?

This is in a Snack Break problem:

local examples = {
	{1, 2, 3}, -- list
	{a = 1, b = 2, c = 3}, -- dictionary
	{a = 0, 1, 2, 3}, -- mixed
	{function() end, newproxy(), "string"}, -- functions, userdata, and strings
	{a = 0} -- with metatables
}

for _, example in next, examples do
	print(tableToString(example))
end

What are the advantages of using for _, example in next, examples do over an in pairs loop?

1 answer

✓ Accepted answer

There is no real advantage or disadvantage. It may be very slightly faster than using pairs, but micro-optimizations are never good justifications.

This is more or less the definition of pairs:

function pairs(t)
	return next, t
end

So it's pretty much the same thing to use next, t and pairs(t).

What is next?

next is the interesting magic that makes it possible to traverse a table.

You give it a table and a key, and it tells you a next key to look at.

local tab = {apple = 1, banana = 2, orange = 3, melon = 4, tangerine = 5}

print(next(tab)) -- melon, 4
print(next(tab, "melon")) -- banana, 2
print(next(tab, "banana")) -- apple, 1
print(next(tab, "apple")) -- tangerine, 5
print(next(tab, "tangerine")) -- orange, 3
print(next(tab, "orange") -- nil

note: next (and pairs since it relies on next) does not return things in any particular order. If you keep re-running the above script, you're probably going to get different answers.

How does next work?

Tables in Lua are implemented as Hashtables.

This means they are blocks of memory that get labeled with keys (in random order) and containing values.

Since it's just a block of memory, guaranteed to be relatively packed with values, it's fairly easy to do what next does, at least in C.

It is not possible to implement next in Lua.

Which do I use?

Some will say it's better to use next because that's what's really happening underneath.

Some[^1] will say it's better to use pairs because it's clearer what you mean.

As with all style choices, the most important thing is to be consistent.

[^1]: e.g., me! Opinion: reserve next for only when you need it (which is only very rarely)

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