I've used them before, but not properly, and still don't know how to use them properly, and when to. I understand that they're simple, but my question is, when do I use them?
You generally don't need to use next
because pairs
is a more obvious way to iterate over a table. The one rare use of next
is quickly finding a single key within a dictionary, usually to determine whether or not the dictionary is empty:
local isEmpty = next(dictionary) == nil
However, actually needing to do this is rare; generally you would have another structure that tells you about the dictionary, such as a list of keys you have been maintaining. Beyond finding an initial key, next
is a bit tricky to think about, so I would recommend sticking with pairs
if you want to iterate over the whole thing.
select
is quite useful if you're using Lua "tuples" (...
). However, I find that tuples are generally not the best way to express myself in Lua; there are very few cases where the tuple is going to work and survive refactoring without being turned into a table. There are performance benefits of using tuples (much less allocation), but it's generally not enough to micro-optimize there until you have measured that it is a problem.