Hello,
I wanted to break out of a while-loop when a pushbutton is clicked on a figure, so I wrote the code below.
function callbackTest1uicontrol('Style','pushbutton',... 'String','I''m done...',... 'Position',[100 100 100 100], ... 'Callback','pressed=1');pressed = 0;while(1) if pressed disp('button pressed') break end pause(0.1)endend
But, when I click the pushbutton, 'pressed=1' is displayed on command window and it does not get out of while loop.
In addition, it is suggested that 'disp('button pressed')' part can't be reached which I really don't understand.
On the other hand, the code below works as expected.
The only thing changed is that it's a script, not a function. Everything else is the same.
% callbackTest_script
uicontrol('Style','pushbutton',... 'String','I''m done...',... 'Position',[100 100 100 100], ... 'Callback','pressed=1');pressed = 0;while(1) if pressed disp('button pressed') break end pause(0.1)end
Weird thing is that the same suggestion (disp('button pressed') can't be reached) is displayed but it works fine.
Finally, I figured out that I have to write the code like this.
function callbackTest2uicontrol('Style','pushbutton',... 'String','I''m done...',... 'Position',[100 100 100 100], ... 'Callback',@press); pressed = 0; function press(~,~) pressed = 1; endwhile(1) if pressed disp('button pressed') break end pause(0.1)endend
1) Why does callbackTest1 not work while callbackTest_script does?
2) In callbackTest1 and callbackTest_script, why can't "disp…" be reached?
3) Anything else I should know about what's behind the behavior of callback function?
4) Is there a better way to do this than callbackTest2?
Thank you.
Best Answer