metatable confusion

this works, i’m just not clear in my head why :S

[lua]local button1 = display.newRect(0,0,100,100)
button1:setFillColor(255,255,255,255)
button1.name=“button1”

local button2 = display.newRect(0,100,100,100)
button2:setFillColor(0,255,255,255)
button2.name=“button2”

function wrapObject(button, event)
print(button.name, tostring(event))
end

local buttonProto={}

function buttonProto:createWrap(event)
wrapObject(self,event)
end

– #### confusion
– i thought this would be (button1,buttonProto) !!?
setmetatable(buttonProto, button1)
setmetatable(buttonProto, button2)

button1.enterFrame=buttonProto.createWrap
button1:addEventListener(“enterFrame”, button1)

button2.enterFrame=buttonProto.createWrap
button2:addEventListener(“enterFrame”, button2)

Runtime:addEventListener(“enterFrame”, button1)
Runtime:addEventListener(“enterFrame”, button2)[/lua] [import]uid: 6645 topic_id: 8185 reply_id: 308185[/import]

whereas this does make sense to me
[lua]local button1 = display.newRect(0,0,100,100)
button1:setFillColor(255,255,255,255)
button1.name=“button1”

local button2 = display.newRect(0,100,100,100)
button2:setFillColor(0,255,255,255)
button2.name=“button2”

function wrapObject(button, event)
print(button.name, tostring(event))
end

local buttonProto={}

function buttonProto:createWrap(event)
wrapObject(self,event)
end

buttonProto.enterFrame = buttonProto.createWrap

button_mt = {__index = buttonProto}

setmetatable(button1, button_mt)
setmetatable(button2, button_mt)

button1:addEventListener(“enterFrame”, button1)
button2:addEventListener(“enterFrame”, button2)

Runtime:addEventListener(“enterFrame”, button1)
Runtime:addEventListener(“enterFrame”, button2)[/lua]

both appear to do the same result though [import]uid: 6645 topic_id: 8185 reply_id: 29190[/import]

In the first example, since you set button1 and button2’s enterFrame property, there’s no reason to access the metatable, so it calls buttonProto’s createWrap.

In the second example, button1 and button2 don’t have ‘enterFrame’, so when trying to index the property, it fails, checks it’s metatable and finds __index is set to buttonProto and then calls createWrap.

Correct me if I’m wrong. [import]uid: 27183 topic_id: 8185 reply_id: 29219[/import]

ah yes thanks. i was trying out different scenarios and must’ve ended up with a version that didnt need the metatables, but before I changed it, it did. doh! [import]uid: 6645 topic_id: 8185 reply_id: 29234[/import]