Like subroutines, functions are units composed of a series of script commands. Functions differ from subroutines in that they may be used in a command, and may return a value (e.g., if the function requested a response from the user, or performed a data transformation).
Example: Calculate a Mean Value
In the example below, the DoMean function is passed two parameters (total and count). Total is divided by count (using the “/” operator) to determine the value for DoMean. This script is entered on the User Script window to define the DoMean function.
|Function DoMean(total As Double, count As Integer)As Double|
|DoMean = total/count|
Once it is entered in the User Script, the DoMean function may be used at any time during the experiment. The CalcMean InLine object below calls the DoMean Function to calculate the mean of 5 randomly chosen numbers. To run this example, after entering the script above on the User Script window, enter the script below on the Setup InLine object.
|Dim total As Double|
|Dim count As Integer|
|Dim i As Integer|
|Dim next_val As Integer|
|total = 0|
|count = 5|
|For i = 1 To count|
|next_val = Random (1,20)|
|MsgBox “Value #” & i & “: “& next_val|
|total = total + next_val|
|MsgBox “The total is “ & CStr(total) & “\n” &_|
|“The count is “ & CStr(count) & “\n” &_|
|“The mean is “ & DoMean (total, count)|