Generate Random Number in Global Tag

Is there a simple way to generate a random number in a global tag, so that the tag can run by itself and generate random numbers for itself?

Initial Attempt:

  • Global script with function to generate random number
  • Call global script in runScript in expression

In an expression tag, runScript("import random; random.randint(0, 1000)", 0) should work.

I am using the free and latest version of Ignition.

I tried that originally, but I get an error:

Error evaluating tag: Error parsing script for runScript() expression: SyntaxError: (“no viable alternative at input ‘=’”, (‘expression:runScript’, 1, 9, ‘__RESULT = import random; random.randint(0, 1000)\n’))

Ah, yeah, looks like the single line import syntax won’t work. Make a shared script, with a single defined function:

import random
def randint(lower, upper):
	return random.randint(lower, upper)

Then call it from your expression tag:
runScript("shared.agg.randint", 0, 0, 1000)

Thanks for the suggestion.

My bad that I didn’t mention that was my initial attempt. I update my question above.

I was hoping for something cleaner than this.

The trouble you are experiencing is due to the fact that runScript() is prefixing the string you feed it with an assignment statement to a hidden variable. So the code that actually executes in Paul’s first suggestion looks like this:

__someVar = import random; random.randint(0, 1000)

And then the __someVar value is fished out of the local variable table to feed to the binding. Not valid python.

If you add a real newline to your string expression, you can print dir() to see what that variable name is. You can also assign a constant temporarily, with a newline, import, execute anything, and assign a real return value several lines later.

I am a little lost with what you are saying…could you please give an example?

Use Paul’s second suggestion.