Does next() look for a __pairs metamethod?
Asked Answered
T

1

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?

Tokharian answered 11/4, 2015 at 16:7 Comment(0)
P
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?

Pewit answered 11/4, 2015 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.