Does anybody know actual implementation of lua 5.2. metamethod __pairs
? In other words, how do I implement __pairs
as a metamethod in a metatable so that it works exactly same with pairs()
?
I need to override __pairs
and want to skip some dummy variables that I add in a table.
pairs(table) Lua provides a pairs() function to create the explist information for us to iterate over a table. The pairs() function will allow iteration over key-value pairs. Note that the order that items are returned is not defined, not even for indexed tables.
The use of the __index metamethod for inheritance is so common that Lua provides a shortcut. Despite the name, the __index metamethod does not need to be a function: It can be a table, instead. When it is a function, Lua calls it with the table and the absent key as its arguments.
The first difference between the pairs() and ipairs() function is that the pairs() function doesn't maintain the key order whereas the ipairs() function surely does.
The following would use the metatable meta to explicitly provide pairs
default behavior:
function meta.__pairs(t)
return next, t, nil
end
Now, for skipping specific elements, we must replace the returned next
:
function meta.__pairs(t)
return function(t, k)
local v
repeat
k, v = next(t, k)
until k == nil or theseok(t, k, v)
return k, v
end, t, nil
end
For reference: Lua 5.2 manual, pairs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With