Scripting Subroutines and Functions

Scripting in FRED is a very powerful capability for automating custom calculations or performing iterative tasks that would be difficult to do through the GUI.  When creating scripts, users should think in advance about whether certain portions of the script are likely to be performed more than once through out the script.  Such code blocks should be separated from the Main() subroutine and placed in their own subroutines or functions.  In addition to being easily called from multiple locations within a script, placing blocks of code inside subroutines and functions is generally good practice for keeping the script understandable and well documented.

Functions are blocks of code which, when called, return a single value to the subroutine or function that called it.  For example, the code:

Function myFunc( ByVal a As Double, ByVal b As Double ) As Double

End Function

defines an empty function (doesn’t perform any tasks) which accepts two arguments as data type DOUBLE (a and b) and returns back a single value of type DOUBLE to the calling subroutine or function.  The code:

c=myFunc( 4, 10 )

calls the function “myFunc”, passes it 4 and 10 (a and b in the function definition) and the function return value is stored in a variable “c”.

Subroutines are defined in a similar manner except that the definition does not return a value.  For example, the code:

Sub mySub( ByVal a As Double, ByVal b As Double )

End Sub

defines a subroutine called “mySub” which accepts two arguments as data type DOUBLE and performs some tasks (not included above) but does NOT return any values to the calling subroutine or function.

The attached example *.frs file demonstrates how to define and call a function and subroutine from Main().  Note that the function returns a value to Main() while the subroutine does not.

Download the FRED script: subroutinesAndFunctions.frs