1

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?

Nail'
  • 23
  • 3
  • 3
    Which version of Lua are you running? Try the [online demo](https://www.lua.org/demo.html). – lhf Dec 23 '21 at 18:39

1 Answers1

3

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).

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • I use Lua 5.4.2 which is running under Windows 10 – Nail' Dec 24 '21 at 04:33
  • I ran the following code in the online demo that runs 5.4: ` local t = setmetatable({}, {__pairs = function (self) print "Message from __pairs()" return function () return nil end end}) for k, v in pairs(t) do print(k,v) end ` – Paul Kulchenko Dec 24 '21 at 07:20