Global event key to break while loop

Dear all,
I am currently trying to program an experiment with Coder. I would like to add a global key to end the trial if the participant presses a specific key. My trials consist of visual stimuli that get updated at every screen refresh, their autoDraw state is set to True at the beginning of the trial and to False at the end.
To add the global key, I do the following, which works fine (i.e., the print statement works correctly)

finished = False
def myfunc(finished):
    finished = True
    print('key was pressed', finished)
event.globalKeys.add(key='b', func=myfunc, func_args= [finished])

However, my trials are built as below:

for trial in trials:
    while (finished == False) :
        # Here goes the content of my trial 

       # condition to end the while loop
       if condition_to_break_while_loop:
            finished = True

My problem seems to be that my setting finished = True through the global event key does not seem to have effect within the while loop. While in my output I get the correct statement printed “key was pressed, True” after the b key was pressed, the print(finished) statement within the loop always returns False, until the condition_to_break_while_loop is met and the trial finishes.

Any suggestion on how to get the global key event to work correctly in this context, or other strategies to achieve my goal?

Thanks a lot for any input!

Dear all,

I found a solution to this issue. The problem is that the variable is treated as LOCAL when modified within the function, whereas we need it as GLOBAL for it to have effect in the while loop.

To fix it, flag the variable as global within the function.

def myfunc(finished):
    global finished
    finished = True
    print('key was pressed', finished)

Hope this helps if someone else has a similar problem!

1 Like