Please enable JavaScript to view this site.

DAQFactory User's Guide

Navigation: 5 Sequences & Scripting

5.18 Running commands in a string with the execute function

Scroll Prev Top Next More

There are many cases where you may need to be able to dynamically create code from within a sequence and execute it.  The Evaluate() function allows you do this in an expression, but evaluate is an expression and cannot execute commands like x = 3.  For that, there is the Execute() function.  The execute function treats the string passed to it as sequence script and runs it.  So, for example:

 

execute("MyChannel = 3")

will set the value of MyChannel to 3.  Of course you could have just done MyChannel = 3 directly.  Where the advantage comes is when you need to assemble the script while running.  For example, lets say you have 50 channels named Ch1, Ch2, Ch3,... and you want to set the first n channels to 4:

 

for (private x = 0, x < n, x++)

 execute("Ch"+DoubleToStr(x)+" = 4")

endfor

Since you don't know what n is when you wrote the script, you couldn't do this without execute.

Execute can actually run more than one line separating each line with a Chr(10).  For example:

 

private strScript

strScript = "global x = 3" + chr(10)

strScript += "global y = 4" + chr(10)

execute(strScript)

Execute allows a lot of flexibility, but really should only be used when necessary for two reasons: 1) it runs slower then regular script because each time the execute() function runs, it has to compile the sequence, and 2) it can make your code harder to read.  

Just a reminder: the Evaluate() function and the Execute() function are nearly the same, except that Evaluate() must be on the right side of an equal sign or in a place that expects an expression, while Execute() can be anywhere (though really should not be in places that expect an expression).  If you put Execute in a place that expects an expression like a screen component, it will always return an empty value.  Evaluate returns the result of the expression in the string parameter.

Note: if you declare a private variable inside the execute(), it is private to the execute() only, so, for example:
 
execute('private x = 3')
? x
 
will fail because X is declared inside the execute().  
 
This can be a little confusing, because execute() runs in the parent scope, so:
 
private x = 2
execute('? x')
 
will work because execute() runs in the scope of the calling function.  Execute() just can't declare privates inside that scope and instead creates the privates in its own scope.  So, this works:
 
execute('private x = 2' + chr(10) + '? x')
 
because we are using the variable x we declared inside the execute() within the execute().