You should not use next()
when pairs()
exists in the environment. The micro-optimization that this originally held has been nullified by Luau improvements.
If you type print(pairs)
into your Studio command bar you will see “function 0x…”, which is just the location of the pairs function in memory. The pairs function correlates exactly to the following code:
function pairs(t)
return next, t, nil
end
So, a traditional for loop actually expands to this:
for i,v in next, t, nil do --[[Code]] end
Okay, that isn’t too complicated, now we look at what next()
actually means.
next(v, v2)
is a function with an optional second parameter. The first parameter represents what table is being indexed upon, and the second parameter is the current index. It will return the next index and value available. Here’s an example with code so you can understand it better:
local this = {
true, false, 10
}
local Index, Value = next(this)
print(Index) --> 1
print(Value) --> true
local Index2, Value2 = next(this, Index)
print(Index2) --> 2
print(Value2) --> false
A generic for loop does a lot of complex work for you. It calls a factory function to receive an iterator function. It calls that iterator function for as long as it can. And lastly, it stops calling the iterator function when it returns nil
. It is essentially equivalent to an unending while ... loop
(but does end when receiving nil).
So, you can now start to see where next()
comes into play. for
expects up to three things. It expects an iterator, a state, and an initial value. It works like this:
local function Factory()
local Upvalue = 0
return function() -- iterator function
Upvalue = Upvalue + 1
if Upvalue < 10 then
return Upvalue
else
return nil
end
end
end
for index in Factory() do
print(i)
end --> 1 ... 2 ... ... 9
Under this context it’s fairly easy to see where pairs()
comes into play to traverse tables and will automatically return nil
when the final index is reached.