Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Corona SDK - Call an instance method or class method from an eventListener

Tags:

lua

coronasdk

I've got a Foo class (well, a pseudo-class) set up as follows:

--in foo.lua
Foo = {}

--constructor
function Foo:new(x, y)
  --the new instance
  local foo = display.newImage("foo.png")
  -- set some instance vars
  foo.x = x
  foo.y = y
  foo.name = 'foo'    

  --instance method
  function foo:speak()
    print("I am an instance and my name is " .. self.name)
  end

  --another instance method 
  function foo:moveLeft()
    self.x = self.x - 1
  end

  function foo:drag(event)
    self.x = event.x
    self.y = event.y  
  end

  foo:addEventListener("touch", drag)

  return foo
end

--class method
function Foo:speak()
  print("I am the class Foo")
end

return Foo

I want the event listener on the foo object to call foo:drag on that same instance. I can't work out how, though: at the moment it's calling a local function called "drag" in my main.lua, which i'm then passing back to the instance. Can i call the instance method directly from the listener? I'm reading about listeners here http://developer.anscamobile.com/reference/index/objectaddeventlistener but am kind of confused :/

thanks, max

like image 836
Max Williams Avatar asked Feb 20 '23 23:02

Max Williams


1 Answers

There are 2 different types of event listeners in Corona, function listeners and table listeners. The local function you mention works because that function is called directly when the event triggers. Corona doesn't support passing table functions, so passing drag in this instance won't work.

To get this working, you need to use the table listener like this:

function foo:touch(event)
  self.x = event.x
  self.y = event.y  
end

foo:addEventListener("touch", foo)

This works because the event listener will try to call the function within table foo with the same name as the event - in this example "touch".

If you need to keep the function name as drag, you can work around this limitation by adding this after the function definition:

player.touch = player.drag

This basically redirects the touch call to your drag function.

like image 180
aaronjbaptiste Avatar answered Mar 15 '23 23:03

aaronjbaptiste