Difference between using "for i,v in pairs() do" and "for i, v, in next, table do"?

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    What is the difference between using:
for i, v in pairs(table) do

end

and

for i, v in next, table do

end
  1. What is the issue? Include screenshots / videos if possible!
    Which one should I use and which one is more efficient?

  2. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

2 Likes

tl;dr They’re exactly the same. pairs is just a convenience function which returns the next function:

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

More info:

For loops are slightly more complicated in general. You can read some deep details here: Programming in Lua : 7 (it talks about pairs vs next in section 7.3).

I’ll try to summarize:

next is a function that, given a table and some key, returns another key, value pair in some arbitrary order. If you give it a nil key, it gives you the first in the order. If it returns nil, it’s done.

For example:

local t = {[4]="d", [3]="c", [2]="b", [1]="a"}

local k, v = nil, nil

k, v = next(t, k)
print(k, v) -- 3, c

k, v = next(t, k)
print(k, v) -- 2, b

k, v = next(t, k)
print(k, v) -- 4, d

k, v = next(t, k)
print(k, v) -- 1, a

k, v = next(t, k)
print(k, v) -- nil, nil

Your for loop just does i, v = next(table, i) over and over (starting with i=nil) until next returns nil.

2 Likes

There is no difference.
This is the same thing as pairs.

local function pairs(table)
    return next, table
end

However:
This is the sort of thing you should search instead of posting. It’s not just a rule, but it can bother the frequent people here. It’s been answered a few dozen times already in far better ways than I can hope to answer.

2 Likes