A Function differs from a Method in one important way. A Function returns some type of data to the code that called it. We will see what this means as we go about creating a Function.
Creating a Function
To add a function to a window open the window code editor. Then select “New Method… ” from the Xojo edit menu. A Method editor sheet appears. Here you enter a name for the method and, if desired, any parameters that the method will use. So far the process is identical to creating a method. However, our function will return data to the code that calls it and we need to specify the Return Type. In this case the return type is “String”.
You can use the popup menu to the right of the Return Type field to select a type.
When you click the OK button the code editor opens ready for you to enter the code for your function. Note, in contrast to a method where the top line begins with “Sub”, the top line of the function begins with the word “Function”. At the end of the top line the return type is indicated (As String).In the example below, the function is expecting a string (“theWords”). It will use thelen function to count the characters. Next, the str function will be used to convert the number into a string.
The result (theCount) will be passed back to the PushButton code that called the CountCharacters function.
The PushButton code will then place the result into EditField1.
The actual flow of the code goes like this:
– PushButton1 sends CountCharacters a string (theWords).
– CountCharacters counts the characters in theWords and passes the result back to PushButton1.
– PushButton1 receives the result and places it in Editfield1.