G-GDK / User defined functions/procedures

Saturday 12 February 2022, by AmiDARK // Principles

User defined functions
Grimoire allow you to create your own Procedure. It’s a priceless feature of the Grimoire GDF. You cannot write effective code without using procedures.

Procedure are blocks of commands that usually perform a recursive or isolated task that is frequently used by your program. Variables defined and used within the function are isolated from the rest of the program. If you use a variable name of MYVAR in your procedure, it will not affect another variable called MYVAR in your main program, nor any other function that happens to use a similar variable name. This may seem to be a restriction, but forces you to think about cutting up your program into exclusive tasks which is a very important lesson.

Procedure ProcedureName
SetString Local1,<"String created locally for the procedure">
logString Local1
EndProcedure

You can pass up to sixteen parameters into your procedure, and have the option of returning a value when the function returns. Functions that do not return a value can also be used as normal commands in your main program.

Each procedure’s parameter must be defined with 2 informations separated by a comma.
- The parameter name
- The parameter type
A comma must be used between 2 parameters definitions.

Each parameters must be defined with 2 informations separated by a comma.
- The parameter name
- The parameter type
A comma must be used between 2 parameters definitions.

Declaring a function/procedure couldn"t be simpler. To use the PROCEDURE command, simply provide it with a name and a list of parameters with type, separated by a comma as explained above, and your declaration is half-complete. Enter the commands you want on the following lines and then end the function declaration with the command ENDPROCEDURE . The following example declares a function that returns requires a string as input, will log the input string in the console, and return a [backup of a] locally created string :

Procedure ProcedureName,FromGlobal,AsString
logString FromGlobal
SetString Local1,<"Here is a String created locally for the procedure zeTest">
logString Local1
SetString Local2,<"Here is the String returned from the Procedure using getProcedureReturn">
EndProcedure Local2

To call the function, you simply have to call it using the MACRO :

callProcedure ProcedureName,GlobalString1

GlobalString1 is an existing String variable.

To get the procedure returned string you simply have to use in an existing variable :

getProcedureReturn returnedString

Of course, the type of the returned value and the variable that receive it must be the same.

A procedure can call another procedure or itself (recursive use). A buffer is defined to limit the amount of imbricated calls of procedures by procedure.