[SOLVED] How do global variables work in scripting?

Good afternoon,

I have the following code running from a pushbutton on my Vision client:

x = system.tag.read('[client]HMI/x').value

def myFunc():
    y = x
    if y == 0:
        return 0
    else:
        return y

Sometimes when I press the pushbutton I get the correct value of x and other times I get zero. Does anyone know why?

Where is the above code? In the button? Or in a script module? If the latter, the assignment to x will only happen once, when the script module loads.

It’s in a script module. Doesn’t the script module load again each time I call a function from a script? For example if I had two buttons calling buttonA and buttonB wouldn’t I get 5 twice? Or would I get an error since x isn’t defined in buttonB().

x = system.tag.read('[client]HMI/x').value ## THIS EQUALS 5

def buttonA():
    y = x
    if y == 0:
        return 0
    else:
        return y

def buttonB():
    y = x
    if y == 0:
        return 0
    else:
        return y

No. That’s the point of a script module–loads once. Running the “def” statement creates the function as a named object, nicely not-quite-compiled, so it runs fast when you call it.

1 Like

Consider reading up on python’s import statement and how imported modules are run just once upon load.

The difference with Ignition is I never have to import anything to run the script. So my final question then is if I have a script module with 100 functions at what point will the script module be compiled and brought into memory? The first time I call a function?

At least by then, but it could be earlier. You can put a logging statement in the top level of the script to see when it fires.

1 Like