lua __pairs的实际实现是什么? [英] what is actual implementation of lua __pairs?
本文介绍了lua __pairs的实际实现是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道lua 5.2的实际实现吗?元方法__pairs
?换句话说,如何将__pairs
实现为元表中的元方法,以使其与pairs()
完全相同?
我需要重写__pairs
,并想跳过一些我在表中添加的虚拟变量.
解决方案
以下内容将使用元表元来显式提供pairs
默认行为:
function meta.__pairs(t)
return next, t, nil
end
现在,要跳过特定元素,我们必须替换返回的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
供参考: Lua 5.2手册,成对 >
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.
解决方案
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
这篇关于lua __pairs的实际实现是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文