Functions


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.

func

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>]

7
>>

Demonstrating that variables are global:

7
7
>>

function

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 func:

Different results:

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 datatype:

*** Script Error: mysum does not allow float! for its a argument
*** Where: mysum
*** Stack: mysum 
>>

You may allow multiple datatypes:

7.2
>>

Or use an upper class of datatypes:

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 return:

Last evaluation example:

5
>>

return example:

15
>>

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>

does

If your routine just do something with no arguments and no local variables, use the word does :

Hello
Stranger
>>

has

If your routine uses no external arguments but has local variables, use the word has. 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.

exit

Exits a function without returning any values.

results matching ""

    No results matching ""