Max Williams
Max Williams

Reputation: 32933

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

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

Upvotes: 4

Views: 3124

Answers (2)

aaronjbaptiste
aaronjbaptiste

Reputation: 554

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.

Upvotes: 5

Corey
Corey

Reputation: 5818

I've had a similar issue with event listeners. I solved it with something like this:

foo:addEventListener("touch", function(e) { self:drag(e); });

I use Middle Class for OOP programing in Lua (which I really recommend)...so I'm not sure if this will work in your scenario. Hope it helps.

Upvotes: 3

Related Questions