Why can't I add a method to an array element yet I am able to do so for the same object by another reference? I assume I have a syntactical error. Originally posted this on the wrong forum so I hope I get more of a response here :)
1 2 3 4 5 6 7 8 9 10 | myRect = {}; myRect[1] = display.newRect(0, 0, 100, 100) mR = myRect[1]; -- both reference the same table print ( myRect[1] ) print ( mR ); function mR:tap (event) end; --this works! function myRect[1]:tap (event) end; --this doesn't work! |
Solved it with info from an old post in case you're curious http://developer.anscamobile.com/forum/2010/07/03/when-functions-are-defined-module-what-difference-between-these-two-types
Urm, from what I gather you are trying to perform a touch event from an object.
The function you are creating, the bit where you write mR:tap / myRect[1]:tap are basically the function names, which on the second one references to a table... not sure if either of these things are supported or do what you intend to do but I think the 'normal' way would be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | local myRect = {} myRect[1] = display.newRect(0, 0, 100, 100) local mR = myRect[1] -- both reference the same table print ( myRect[1] ) print ( mR ) local function mRtap (event) -- do something end function myRectTap (event) -- do something end myRect[1]:addEventListener("touch", mRtap) mR:addEventListener("touch", myRectTap) |
Given 10 rectangles, I assume you setup 1 listener for all of them and detect which rectangle was touched using phase and modify it as desired.
I'm doing the same but in an object oriented manner where each object has it's own listener. 10 in this case (1 for each rectangle).
Your approach seems like a better design where oop/encapsulation is not a concern. Can you tell me if there are downfalls of having multiple listeners as in my approach?
Thanks!