what is actual implementation of lua __pairs?

心不动则不痛 提交于 2019-12-07 02:30:38

问题


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 


来源:https://stackoverflow.com/questions/23624248/what-is-actual-implementation-of-lua-pairs

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