luametatablemeta-method

Does next() look for a __pairs metamethod?


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?


Solution

  • 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?