Hello,
I am refactoring a lot of my code right now, and I came up with an idea to simplify the loads of touch listeners I use in the game. Most of em look pretty much the same, so I made a helper class that creates a default touch listener for me. It handles the setFocus and disables the touch when touches in my game should be.
The helper looks like this:
local t = {} function t:getDefaultTouchListener(\_options) local \_onPress = \_options.onPress local \_onMoved = \_options.onMoved local \_onRelease = \_options.onRelease local \_shouldEndWithinBounds = \_options.shouldEndWithinBounds local touchEvent = function(event) if inputHelper:isTouchesBlocked() then return true end if event.phase == "began" then display.getCurrentStage():setFocus(event.target) event.target.isFocus = true if \_onPress then \_onPress(event) end elseif event.phase == "moved" and event.target.isFocus then if \_onMoved then \_onMoved(event) end elseif (event.phase == "ended" or event.phase == "cancelled") and event.target.isFocus then display.getCurrentStage():setFocus(nil) event.target.isFocus = nil if \_onRelease and (not \_shouldEndWithinBounds or widget.\_isWithinBounds(event.target, event)) then \_onRelease(event) end end end return touchEvent end return t
And usage looks like this
local onTouch = touchEventHelper:getDefaultTouchListener{ onMoved = function() print "onMoved" end, onPress = function() print "onPress" end, onRelease = function() print "onRelease" end } parentGroup:addEventListener("touch", onTouch)
This works perfectly!
but I am curious if this is LUA correct, if I don’t create memory leaking or make stuff slower. As I read passing anonymous functions could slow down code a bit? (or did I solve this by localizing the parameters?)