user2136963
user2136963

Reputation: 2606

Create event listener with parametrs Lua

I need to create enterFrame listener with more parametrs than just event. I've read this: addEventListener() in Lua The first way, to use

local function listener(param1, param2)
     return function(event)
          print(event.name, event.phase, param1, param2)
     end
end    
Runtime:addEventListener("touch", listener(12, 33))

worked nice, but now I have a problem with deleting this enterFrame listener.

Runtime:removeEventListener("enterFrame",listener);

doesn't work because the function name is not "listener". How can I delete it?

Upvotes: 2

Views: 1663

Answers (1)

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

You can cache the functions you are creating, such that listener(x, y) will always return the same one. Something like this may work:

local listeners = {}
local function listener(param1, param2)
     -- add some separator, so 1,12 is different from 11,2
     local key = param1.."\1"..param2
     listeners[key] = listeners[key] or function(event)
          print(event.name, event.phase, param1, param2)
     end
     return listeners[key]
end

Since listener(12, 33) will always return the same result, now you can do Runtime:removeEventListener("enterFrame",listener(12,33))

Upvotes: 1

Related Questions