8

In general, the syntax:

for k, v in pairs(t) do
   ....
end

is equivalent to:

for k, v in next, t do
    ....
end

But what if t has a __pairs metamethod? Will the standard next() function check for this? If not, isn't it better to always use pairs when iterating over tables, and never call next() directly?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Siler
  • 8,976
  • 11
  • 64
  • 124

1 Answers1

5

No, next() doesn't check for __pairs. The manual doesn't say so.

It can be double confirmed from the related source code, compare luaB_pairs and luaB_next.

There might be times when you don't want to check for __pairs metamethod, so why say always use pairs over next?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294