__pairs() and __ipairs() metamethods does not work at all

623 Views Asked by At

I don't know what I do wrong. Basically the code looks like this:

local t = setmetatable({}, {__pairs = function (self)
    print "Message from __pairs()"
    return function ()
        ...
    end
end})
for k, v in pairs(t) do ... end

The same for __ipairs(). Overloaded metamethods aren't called at all - no console output, no custom iteration at all. Instead I get the result as if I iterate through a table without metatable. What's wrong?

2

There are 2 best solutions below

2
Paul Kulchenko On

You most likely use Lua 5.1 (or its derivative), which doesn't have support for these metamethods, as these were introduced in Lua 5.2. I've tested in Lua 5.2-5.4 and confirmed that your code works there (the method is called).

0
shtse8 On

for those who are not working on __pairs and __ipairs in older versions (for example, Solar2D is running on Lua 5.1), you can override the pairs and ipairs functions to add supports in main.lua using the following code:

local raw_pairs = pairs
pairs = function(t)
    local metatable = getmetatable(t)
    if metatable and metatable.__pairs then
        return metatable.__pairs(t)
    end
    return raw_pairs(t)
end

local raw_ipairs = ipairs
ipairs = function(t)
    local metatable = getmetatable(t)
    if metatable and metatable.__ipairs then
        return metatable.__ipairs(t)
    end
    return raw_ipairs(t)
end