I discovered something well messing around with for loop anybody know why this works

It appears that you don’t need i in for loop at all? i was just messing around and some how
i figured out that the you don’t need 2 values for the loop!

did anybody know about if so
is it useful or is it pretty obscure

Tab = {2,4,6,8}

for index in next, Tab do
print(index)
end

versus the normal i,v or foo,foo

2 Likes

You can do the same thing on the for i, v in pairs(Table) loop. This is not a glitch nor a mistake, But it was supposed to work like this.

2 Likes

In terms of overall behaviour, i, v loops actually are the same as next since pairs uses next. If you want to know more about next loops I’d recommend checking this guide for next() loops.

1 Like

i don’t use next very often but it seems pretty cool

1 Like

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.

1 Like