Functions must be declared before they are used and so must be written on top of your program. However, this is not required if a function is called from within another function.
Variables inside a function created with
func are global. They are the seen by the entire program.
A function is created with
func as follows:
<function name>: func [<argument1> <argument2> ... <argument n>] [ <actions performed on arguments>]
Demonstrating that variables are global:
7 7 >>
function makes its variables local, i.e. it hides (shades) the variables inside it from the rest of the program.
Same program as above, only using
function instead of
7 20 >>
Forcing variables to be global with /external refinement:
22 9 >>
Defining the argument type:
You can force your arguments to be of a certain
*** Script Error: mysum does not allow float! for its a argument *** Where: mysum *** Stack: mysum >>
You may allow multiple
Or use an upper class of
Returning values from functions:
The return value of a function is either the last value evaluated by the function or one explicitly determined by the word
Last evaluation example:
Creating your own refinements:
You can create refinements to you functions, like the native refinements of Red: <myfunction>/<myrefinement>. The refinements are boolean values that are checked by the function:
13 7 >>
Note that arguments are not mandatory for refinements.
Assigning functions to variables
To assign a function to a variable (a word) you must precede the function with a colon: <word>: :<function>
If your routine just do something with no arguments and no local variables, use the word
Hello Stranger >>
If your routine uses no external arguments but has local variables, use the word
has turns the argument into a local variable. Compare the three programs below. The first uses
has with no argument, hence
number is a global variable. The second gives
number as argument, making it local. And the third shows that a function with argument need that argument to be sent by the calling event.
Exits a function without returning any values.