Why does this work?

Recently I have been using

for i, v in next, t do

But I don’t quite understand why this syntaxing actually works.

pairs actually returns next.

function pairs(t)
    return next, t, nil
end
1 Like

thats pretty unrelated, I want to know why my code works, not the code that uses the code to work.

I’m not too sure how to explain it, but next returns part of the table. ex:

local tbl = {1, 3}

print(next(tbl, 1)) --2, 3
print(next(tbl)) --1, 1
print(next(tbl, 2)) -- nil or nil, nil

Now, I’m thinking that for i,v in continues until the function inside returns nil. Not many people know exactly why it works like that (including myself), so there’s not much I can say.

The part I’m really interested about is where it goes

next, t

Where it calls next with its last return

Again, I’m not exactly sure how it works, but I’m assuming the code for for i,v in handles the next code by calling the second variable you provided

next(t)

and running onto that, then calls

next(t, i)

for the next iteration.