I see. This is a two part answer…
One
I think you’d well served reading the tutorials and guides here.
In this context, these specifically:
Two
Let me give you some examples that build up into a solution.
The Basic Touch Listener
-- -- This listener assumes you want to call a function when lifting your finger. -- It doesn't handle highlighting the button or any other visual effects. -- It also doesn't handle sliding your finger off the button and lifting your finger. -- It assumes the object has a function called 'onRelease' -- It is very basic and not good for usability, but it will do the basics. -- local function onTouch( self, event ) if( event.phase == "ended" ) then self.onRelease() end return false end
A Button Builder That Uses The Listener
local function createPushButton( x, y, width, height, imgPath, onRelease ) local button = display.newRect( imgPath, width, height ) button.x = x button.y = y button.onRelease = onRelease button.touch = onTouch button:addEventListener("touch") return button end
Making A Module
Now, lets take all of the code above an put it a module to make it portable and easy to use.
-- simpleButton.lua local m = {} local function onTouch( self, event ) if( event.phase == "ended" ) then self.onRelease( self ) end return false end function m.createPushButton( x, y, width, height, imgPath, onRelease ) local button = display.newRect( imgPath, width, height ) button.x = x button.y = y button.onRelease = onRelease button.touch = onTouch button:addEventListener("touch") return button end return m
Using The Module
local simpleButton = require "simpleButton" local function myListener( self ) print( "Just pressed button ID: ", self.id ) end local tmp = simpleButton( 100, 100, 100, 30, "image1.png", myListener ) tmp.id = 1 local tmp = simpleButton( 100, 150, 100, 30, "image2.png", myListener ) tmp.id = 2 local tmp = simpleButton( 100, 200, 100, 30, "image3.png", myListener ) tmp.id = 3