[SOLVED] Error when adding an event listener to a sprite within an instanciated object

I’ve created a class that will generate an object with a sprite, and I want to add an action listener to its sprite to change its animation when I tap on it, so I have the following code:

sprite = require "sprite"  
  
Defensa1 = {x,y, sprite}  
function toggle(self,event)  
  
 self:prepare("attack")  
 self:play()  
end  
function Defensa1:new(x,y)  
  
 instancia = {}  
  
 setmetatable(instancia, self)  
  
 self.\_\_index = self  
  
 sheet1 = sprite.newSpriteSheet( "defensa1.png", 200, 163 )  
  
 spriteSet = sprite.newSpriteSet(sheet1,1,25)  
  
 sprite.add( spriteSet, "walk", 1, 15, 800, -2)   
 sprite.add( spriteSet, "attack", 15, 11, 500, -2)   
  
 instancia.sprite = sprite.newSprite(spriteSet)   
  
 instancia.sprite.x = x  
 instancia.sprite.y = y  
  
 instancia.sprite:prepare("walk")  
 instancia.sprite:play()  
  
 instancia.sprite:addEventListener("tap", toggle)  
  
 return instancia  
  
end  

When i run it and tap over the sprite it gives me this error: Runtime error: attempt to call method ‘prepare’ (a nil value) in function “toggle”. What am i doing wrong? Thanks in advance for your reply! [import]uid: 183642 topic_id: 35448 reply_id: 335448[/import]

I’ve found the solution, I dont know where I saw that you can implement a listener with 2 parameters (self, event)… Actually this is wrong. The way I fixed this is with the following listener:

function toggle(event)  
  
 event.target:prepare("attack")  
 event.target:play()  
  
end  

and

instancia.sprite:addEventListener("tap", toggle)  

to simple assign that listener…

Thanks for reading my problem anyway [import]uid: 183642 topic_id: 35448 reply_id: 141019[/import]

I’ve found the solution, I dont know where I saw that you can implement a listener with 2 parameters (self, event)… Actually this is wrong. The way I fixed this is with the following listener:

function toggle(event)  
  
 event.target:prepare("attack")  
 event.target:play()  
  
end  

and

instancia.sprite:addEventListener("tap", toggle)  

to simple assign that listener…

Thanks for reading my problem anyway [import]uid: 183642 topic_id: 35448 reply_id: 141019[/import]