Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
Siler Avatar asked Apr 11 '15 16:04

Siler


1 Answers

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?

like image 115
Yu Hao Avatar answered Sep 17 '22 11:09

Yu Hao