Passing Parameters in Event Listeners + tables

Okay, so I am trying to keep my code short in my game so I can quickly and (practically) effortlessly change something if I needed to. Therefore I have been using tables to create similar objects, place them, create their event listeners, remove them, etc. However I was wondering how you could possibly pass a number between an event listener and a function.

The code explains it:

local function gotolevel(event, number1)
    if(event.phase == “ended”) then
        print(“hi”)
        if(event.target.alpha > 0.9) then        – If its alpha is not 1, then you can’t go there
            print("level "…number1)
            storyboard.gotoScene(“level”…tostring(number1), options)
        else
            print(“can’t go there”)
        end
    end
end

for i = 1, 3 do
        box[i]:addEventListener(“touch”, gotolevel, i)           --I want it to pass what number box it is

end

Basically I want the boxes to pass their number and then whenever they are called, the function would go to the correct scene. Please point out any errors you see.

You really can’t do what you want to do, at least not the way you think you want to.  Because of the way eventListeners work, you can’t setup parameters like that.  What you have to do is add some value to your box object giving it some identifying value.  Some people will call it “name” others “id”:

Where ever you create box[i] do:

box[i].id = i

Then in your gotoLevel( event ) function, you can get to the “i” value by doing:

   local thisBoxId = event.target.id

Rob

Thanks again! It works!

You really can’t do what you want to do, at least not the way you think you want to.  Because of the way eventListeners work, you can’t setup parameters like that.  What you have to do is add some value to your box object giving it some identifying value.  Some people will call it “name” others “id”:

Where ever you create box[i] do:

box[i].id = i

Then in your gotoLevel( event ) function, you can get to the “i” value by doing:

   local thisBoxId = event.target.id

Rob

Thanks again! It works!