UI Button problem...

Having an issue I can’t resolve.

I have a function we will call MakeButtons

MakeButtons creates some buttons using UI Library and puts them in a table we will call buttonTable that is called at the top of the app and is Global

Each UIButton calls another function doWhenPressed.
While within MakeButtons everything works as expected. buttonTable[x].isVisible works for example.

doWhenPressed takes the event.id (which is verified to have same value as x). ie buttonTable[x] =buttonTable[event.id]

However buttonTable[event.id].isVisible does not work. In fact buttonTable[x] when x is forced also does not work.

Any clues anyone? [import]uid: 5594 topic_id: 620 reply_id: 300620[/import]

I cleaned up the code so I could post an example
At the top of the program:

 buttonTable={}  

MakeButtons:

[code]
function MakeButtons (numOfCans)

numOfCanNumber=tonumber(numOfCans);
canToPop=5;

local i=1;

while i <= numOfCanNumber do
newButton=ui.newButton{
default = “up.png”,
over = “down.png”,
onEvent = doWhenPressed,
text = " ",
id = i,
emboss = true
}
buttonTable[i]=newButton;
buttonTable[i].y=(math.floor((i-1)/3)+1) * StageHeight/5;
buttonTable[i].x=((i-1) % 3 + 1) * StageWidth/4;
i=i+1;

end;

end;

doWhenPressed:

[code]
function doWhenPressed(event)
if(event.id==canToPop) then
winscenario=true;
else
buttonTable[event.id].isVisible=false;
end;

end
[/code] [import]uid: 5594 topic_id: 620 reply_id: 1224[/import]

I’m no expert in Lua, but I believe at least part of the problem is in doWhenPressed(event).

The event.id is not the same as the id you set in the button above. What you want, I think, is something like:

function doWhenPressed(event)  
 local t = event.target  
 if(t.id == canToPop) then  
 winscenario = true;  
 else  
 buttonTable[t.id].isVisible=false;  
 end  
end  

You need to get the target of the event, which is your button, then you can look at its id.

Sean.
[import]uid: 4993 topic_id: 620 reply_id: 1243[/import]

If I print(event.id), I have it correct index. Verified the type is number as well. [import]uid: 5594 topic_id: 620 reply_id: 1265[/import]

Solved: Bug maybe???

The uiButtons get called multiple times on a single button press. Maybe I am just not following the code well enough. I made a checker to ensure the button only gets pressed once and now everything is fine. [import]uid: 5594 topic_id: 620 reply_id: 1266[/import]

Remember, multiple events get generated each time a button is tapped.

For buttons, I always check that the event type (or “phase”) is “ended”, which means that the user lifted a finger from the button. But there are others, like “began” and “moved” as well. If you look at the sample code, you often see something like

function dosomethingwithbutton(event)  
 local phase = event.phase  
 if "ended" == phase then  

so that the code is only called when the user lifts the finger from the button.

Sean. [import]uid: 4993 topic_id: 620 reply_id: 1271[/import]