what is actual implementation of lua __pairs?
Asked Answered
P

2

7

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.

Plumate answered 13/5, 2014 at 6:34 Comment(1)
lua-users.org/wiki/GeneralizedPairsAndIpairsFibrous
J
4

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

Jacobine answered 13/5, 2014 at 16:0 Comment(0)
F
1

The code below skips some entries. Adapt as needed.

local m={
January=31, February=28, March=31, April=30, May=31, June=30,
July=31, August=31, September=30, October=31, November=30, December=31,
}

setmetatable(m,{__pairs=
function (t)
    local k=nil
    return
    function ()
        local v
        repeat k,v=next(t,k) until v==31 or k==nil
        return k,v
    end
end})

for k,v in pairs(m) do print(k,v) end 
Fruitarian answered 13/5, 2014 at 11:22 Comment(1)
v should be a local. Also, it diverges from the default pairs much more than needed.Jacobine

© 2022 - 2024 — McMap. All rights reserved.