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?
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)
.
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.
Some will say it's better to use next
because that's what's really happening underneath.
Some1 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.
e.g., me! Opinion: reserve next
for only when you need it (which is only very rarely) ↩