what is actual implementation of lua __pairs?

2019-04-28 06:09发布

问题:

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.

回答1:

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



回答2:

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