In cocos2dx Sample, there's code like this:
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
What is setpper & getpeer for?
Those are tolua functions. The tolua manual (for example here) has explanations for them.
tolua.setpeer (object, peer_table) (lua 5.1 only)
Sets the table as the object's peer table (can be nil). The peer table is where all the custom lua fields for the object are stored. When compiled with lua 5.1, tolua++ stores the peer as the object's environment table, and uses uses
lua_gettable/settable
(instead oflua_rawget/set
for lua 5.0) to retrieve and store fields on it. This allows us to implement our own object system on our table (usingmetatables
), and use it as a way to inherit from the userdata object. Consider an alternative to the previous example:
-- 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)
When indexing our object, the peer table (if present) will be consulted first, so we don't need to implement our own __index metamethod to call the C++ functions.
tolua.getpeer (object) (lua 5.1 only)
Retrieves the peer table from the object (can be nil).