Custom functions in Pavlovia


I’m trying to custom define a function which I then use in Python in an auto->JS code component. However, I’m getting the ‘reference error: can’t find variable x’ for the function name. I’ve seen here that I should define it in my JS code block. However, this isn’t working for me. Are there any ideas about how I could do this?

Many thanks :slight_smile:

How have you worded the function definition?

Is it in Before or Begin Experiment?

It is in before experiment. i.e.:

and then I try to use it in a later code component here:

but even though it is defined in the previous code block, it claims it isn’t recognised…

The syntax you are using Before Experiment is the version I use in Begin Experiment.

In Before Experiment I tend to write the function in Python. Try moving your code to Begin Experiment.

Thank you. When you write the function in Python, how do you then make sure that it translates this to JS so you can use it in Pavlovia?

Start by trying something in this format in an Auto Translate component.

def functionName(x):
     do stuff
     return functionOutput

If it doesn’t translate automatically you need to switch the component to Both to edit the JavaScript.