what is actual implementation of lua __pairs?

岁酱吖の 提交于 2019-12-05 06:06:49

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

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!