destroy self if nothing happens

Hi y’all,
as the year starts, I figure it will be a good time to start picking corona back again…I am a bit rusty (with the noobnes, holidays and all :wink:

Anyways, I have this code:

--\>touch function  
-- A touch listener to remove Ball  
local removeBall = function( event )  
 local t = event.target  
 local phase = event.phase  
  
 if "began" == phase then  
 \_G.score = \_G.score + 1  
 t:removeSelf() -- destroy object  
 end  
 -- Stop further propagation of touch event  
 return true  
end  
--\> spawn ball  
local fnBalls = function()  
  
 --\> remove after 3 seconds of appearing if no touch occurred.  
 local fnDestroyBall = function(self)  
 self.parent:remove( self )  
 self = nil  
 end  
  
 --\> create ball object  
 BallsObject = display.newImage( "ball.png" )  
 BallsObject.x = math.random( 380 ); BallsObject.y = math.random( 280 )  
 physics.addBody( BallsObject, "static", {density=5.0, bounce=0, friction=0.5} )  
 BallsObject.myName = "ball"  
  
 --\> wait 3 seconds to destroy self  
 transition.to( BallsObject, { time=3000, onComplete=fnDestroyBall } )  
  
 --\> add touch listener  
 BallsObject:addEventListener( "touch", removeStar )  
  
end  
tmrBallSpeed = timer.performWithDelay( 15000, fnBalls, 0 )  
  

It works as long as I don’t touch the ball and the timer completes; otherwise, I get this error:
attempt to call method ‘remove’ (a nil value)

Any idea?
RD [import]uid: 7856 topic_id: 4835 reply_id: 304835[/import]

in your fnDestroyBall put [lua]print("hello "…tostring(self))[/lua]. my guess is you’ll see this after you touch your ball becuase the transition timer is still completing then trying to find “self” which obviously you’ve removed so will be nill.

you’ll need to store a reference to your transition and then cancel the transition on your touch event

try something like
[lua]BallsObject.myTransition = transition.to( BallsObject, { time=3000, onComplete=fnDestroyBall } )[/lua]

then in fnDestroyBall do something like
[lua]if t.myTransition then t.cancel()[/lua]

i think it should work but i havent tested it [import]uid: 6645 topic_id: 4835 reply_id: 15512[/import]

Thanks jmp909.
I figured it was going to be something silly like that.
As soon as I added the ‘mytransition.cancel()’ function to my ‘removeball’ it worked :wink: [import]uid: 7856 topic_id: 4835 reply_id: 15654[/import]