Global Variable Usage

I am trying to define and use a global variable with no luck.
I need to have a shared array that can be accessed from anywhere.

Actually I am using a memory tag, I want to replace that tag with a global variable.

I tryed to define the variable on the gateway startup script and on a function in project library that is called on the startup script.

from the script console:
g = system.util.getGlobals()[‘Array’]
print g

All I get is:

Traceback (most recent call last):
File “”, line 1, in
KeyError: ‘Array’

How can I achieve this?


Consider storing it in a dataset or document tag.

How can I store on a global dataset?
I think that the problem will persist.

What is a document tag?

What I am trying to do is populate an array (dataset could be ok too) on some tag change event
and with a timer script elaborate all the data with a pop function.

Since system.util.getGlobals() returns a dictionary, when you use the square bracket notation, the system tries to read the value from that key, if that key doesn’t exist then you will a KeyError exception as seen.

You first need to set the value of the global prior to it being called.

#This will create the key if it doesn't exist and set the value
system.util.getGlobals()['myArray'] = [0,1,2,3,4]

#This will print the value of the key, so long as the key exists in the globals dictionary
print system.util.getGlobals()['myArray']

Honestly, a tag is probably the best option here, though depending on the use case a client tag may be more appropriate.

I tryed mainly 2 things:

  1. On Gateway’s startup script I defined a variable:
    Array = [1,2,3]

  2. On a Project Library I defined a Library
    def onStartup():
    Array_Event = [1,2,3]
    and I call the function on the gateway’s startup script

In both way I can not get the array with the getGlobals function

Actually I am using a memory tag like You suggested.
With some test looks like sometime I miss some event if the event come when the scheduled task is running.
I believe that this is because of the 2 task asyncrounism
(one on valuechange and one every 1 second)
or the delay between the and system.tag.write() functions on the 1 second task where I read the array I elaborate the value and then I write the modified array again

I’m Open to suggestion

A short example:

# Path to document tag
globalsPath = '[default]Test/Globals'

# Initialize dictionary
globalVarsOut = {}
#Make up some stuff to add to the dictionary
globalVarsOut['List1'] = [1,2,3]
globalVarsOut['Dict1'] = {'A':101 , 'B':102, 'C':103}

# Encode to JSON
jsonOut = system.util.jsonEncode(globalVarsOut)

# Write to tag
system.tag.writeBlocking([globalsPath], [jsonOut])

# Read the tag
globalVars = system.tag.readBlocking([globalsPath])[0].value.toDict()

# Print some values
print globalVars['List1']
print globalVars['Dict1']
print globalVars['Dict1']['B']


[1L, 2L, 3L]
{'A': 101L, 'B': 102L, 'C': 103L}