<< Click to Display Table of Contents >> Navigation: Basic concepts > Procedures and functions > User Functions |
User functions
You can also write your own functions in GPScript.
Syntax:
Function <name> ([<identifier> : <type> [, <identifier> : <type>]]) [Autotype] [Returns <type>]
<Local variable declarations>
<Statements>
End
Functions must have a unique name. Zero or more parameters can be defined and parameters are always passed in by value. Note that types such as Widgets, Plugins and dynamic arrays are objects and so what's really being passed by value is the reference (a pointer) to the object.
The Autotype keyword is used to let a function be a little (not a lot) more forgiving about the types of the parameters that are passed into it. In the example here, the use of Autotype allows a function to accept integers or doubles (and strings of course):
Function Add(x : String, y : String) Autotype
Print(x + y)
End
Initialization
Add(1, 2)
End
An autotyped function with a MidiMessage parameter will accept calls with specific kinds of messages such as NoteMessage or ControlChangeMessage.
Functions can optionally return a value in which case the Returns clause must be present. If the Returns clause is present, then a variable called result exists in the function scope and whatever is assigned to that variable will be the return value.
There is deliberately no mechanism to return from the middle of a function.
Example:
Function SumNumbers(a : integer, b : integer, c : integer) returns integer
result = a + b + c
End
Function PlayMajorChord(keyboard : MidiInBlock, root : NoteMessage)
SendNow(keyboard, root) // Original note
SendNow(keyboard, WithTranspose(root, 4)) // The third
SendNow(keyboard, WithTranspose(root, 7)) // The fifth
End