I have a question regarding passing a parameter to a function from an event listener.
Not sure that it sounds very clear. Basically, in the example below, when i press the magenta (myButton) rectangle, i want to move the grey rectangle (myRectangle) from a Y distance passed from the listener :
local myRectangle = display.newRect(150, 300, 150, 50)
myRectangle.strokeWidth = 3
myRectangle:setFillColor(140, 140, 140)
myRectangle:setStrokeColor(180, 180, 180)
local myButton = display.newRect(100, 400, 150, 50)
myButton.strokeWidth = 3
myButton:setFillColor(140, 0, 55)
myButton:setStrokeColor(180, 180, 180)
local function moveY (distance)
myRectangle.y = myRectangle.y - distance
end
myButton:addEventListener("touch", moveY(20))
when i now try to use the phase of the event, i run into an error (showed below).
local myRectangle = display.newRect(150, 300, 150, 50)
myRectangle.strokeWidth = 3
myRectangle:setFillColor(140, 140, 140)
myRectangle:setStrokeColor(180, 180, 180)
local myButton = display.newRect(100, 400, 150, 50)
myButton.strokeWidth = 3
myButton:setFillColor(140, 0, 55)
myButton:setStrokeColor(180, 180, 180)
local function moveY (event, distance)
if event.phase == "ended" then -- I get here an 'attempt to index local 'event' (a nil value)
myRectangle.y = myRectangle.y - distance
end
end
local closure = function() moveY(event, 20) end
myButton:addEventListener("touch", closure)
Any idea?
Thanks,
Dim
[import]uid: 100310 topic_id: 24852 reply_id: 100811[/import]
local function moveY( event )
if event.phase == “ended” then
myRectangle.y = myRectangle.y - distance
end
end
myButton:addEventListener( “touch”, moveY )
[/code] [import]uid: 77199 topic_id: 24852 reply_id: 100820[/import]
Well, in this example, yes. But now consider a graphic keyboard of 4 letters (ABCD).
To show what the user is writing, each of these images representing a letter, when pressed, will add their string (“A”, “B”, etc.) to the existing word.
So they will all need an eventListener each calling for a specific function (for example, addAToTheWord, addBToTheWord, etc).
fine with me.
But now, consider that the keyboard is not only 4 letters, but 1000. In that case, you would like to create a generic ‘addToTheWord’ function that takes the character as parameter.
No?
Using the ‘closure’ solution is fine. But if you also want to use the event parameter (for phases for example), then you can’t pass both (event + the character/index as a parameter)
Maybe i am completely wrong in the approach, i’m pretty new to coding.
How would you do that? [import]uid: 100310 topic_id: 24852 reply_id: 101123[/import]