getpeer&的含义setpeer

时间:2014-04-02 13:08:27

标签: lua cocos2d-x tolua++

在cocos2dx Sample中,有如下代码:

function UIButtonTest.extend(target)
local t = tolua.getpeer(target)
if not t then
    t = {}
    tolua.setpeer(target, t)
end
setmetatable(t, UIButtonTest)
return target
end

什么是setpper& getpeer for?

1 个答案:

答案 0 :(得分:2)

这些是tolua功能。 tolua手册(for example here)对它们有解释。

tolua.setpeer (object, peer_table) (lua 5.1 only)
  

将表设置为对象的对等表(可以为nil)。对等表是存储对象的所有自定义lua字段的位置。当使用lua 5.1编译时,tolua ++将对等体存储为对象的环境表,并使用lua_gettable/settable(而不是lua_rawget/set用于lua 5.0)来检索和存储字段。这允许我们在表上实现我们自己的对象系统(使用metatables),并将其用作从userdata对象继承的方式。考虑前一个例子的替代方案:

-- a 'LuaWidget' class
LuaWidget = {}
LuaWidget.__index = LuaWidget

function LuaWidget:add_button(caption)
    -- add a button to our widget here. 'self' will be the userdata Widget
end

local w = Widget()
local t = {}
setmetatable(t, LuaWidget) -- make 't' an instance of LuaWidget

tolua.setpeer(w, t) -- make 't' the peer table of 'w'

set_parent(w) -- we use 'w' as the object now

w:show() -- a method from 'Widget'
w:add_button("Quit") -- a method from LuaWidget (but we still use 'w' to call it)
  

在索引对象时,首先会查询对等表(如果存在),因此我们不需要实现自己的__index元方法来调用C ++函数。


tolua.getpeer (object) (lua 5.1 only)
  

从对象中检索对等表(可以是nil)。