Global Vars Script Declaration and Assignment

I have a script that I use a global variable in to enable logging on a client gateway.

I thought that this should be working, but it doesn't seem to work as expected. Ignition v8.1.16:

I have this script in a "globalVars" project library package.

#global variables

logger = False

#initialize global var values
def start():
	logger = True

The intention is that a startup script for the client gateway runs globalVars.start() and toggles logger to True. However, when I print globalVars.logger in the script console I get False. Even if I try and print it after a direct call to globalVars.start()

def logTagChange2(tag, tagPath, currentVal, initialChange, clientScope=0):

	if globalVars.logger:
		#get values from tag
		.
		.
		.

What am I doing wrong?

Maybe I have a scope issue in the client? I have other scripts that are dependent on this variable as well that definitely are working.

What causes logTagChange2 to be called?

tag change script(s)

A tag change script runs in the Gateway.

A Client Startup script runs in the Client.

Global state/variables are not shared between these 2 entirely separate contexts.

Sorry, yes I misspoke. globalVars.start() is run on a gateway startup script, not client.

I think this needs to be:

#initialize global var values
def start():
    global logger
    logger = True

but also I think there's some standard advice about using system.util.globals instead

3 Likes

I found the actual issue in my script.

I had a lastTime prop and I was comparing it to now to figure out when the time since last log had passed the minimum sample time, but I was doing the comparison backwards. I had lastTime - now instead of now - lastTime

Thanks for the help

I really can't see any way this isn't just shadowing logger inside start. It wouldn't/shouldn't be affecting the variable from the outer scope at all (without the use of the global keyword as Kevin suggested).

For something completely different...
Could you put the initialization of logger into a function and have that function's return value act as the initialization?
That is:

logger = __getInitialState()

def __getInitialState():
    if someComplicatedCondition:
        return True
    else:
        return False

That seems easier to reason about (at least, in this isolated, cut down example you provided) than the current order of operations.

2 Likes

Thanks for the input. I'll take a look at other options for the same functionality.