Methods and Functions | ||
Methods and Functions are blocks of code that you create to perform particular actions. For example, if you wanted to know how many characters were in a particular EditField, you could write a method to do the calculations. As we will see, you could also write a function to do the same thing but in a slightly different way. In the following we will examine both methods as a means of illustrating the difference between methods and functions. | ||
![]() | ||
Creating a Method | ||
To add a method to a window open the window code editor. Then select "New Method... " from the REALbasic 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. In this example we will be passing the CountCharacters method a string of characters. The method will then count the characters in the string we have passed to it. | ||
![]() | ||||
In the Parameters field you can add more than one parameter. Parameters must be separated by commas. | ||||
When you click the OK button the code editor opens ready for you to enter the code for your method. In the example below, the code uses the "len" function to get the number of characters in "theWords". The the "str" function is used to convert the number to a string so it can be displayed in EditField1. | ||
![]() | ||
![]() | ||||
The code in PushButton1 uses our CountCharacters method. It passes the text in EditField2 to CountCharacters as a parameter. | ||||
![]() | ||||
CountCharacters then executes its code "EditField1.text = str(len(theWords))" placing the results in EditField1 | ||||
On the next page we will see how to accomplish the same thing using a Function instead of a Method. | ||