Scripts - User defined functions
Function
Function myfunc([param1,param2,...]) declares a function named myfunc that optionally accepts inputs param1,param2,...
The function may optionally return a value. See Return statement below.
- All variables defined and used in the function are local to the function. They cannot be used in the main body of the script. A variable var used in a function will have other values than a variable with the same name outside the function. This behavior can be changed with the Global function described below.
- A function cannot be defined within another function (nested functions are not allowed).
- After you have defined a function you can also use it in the MedCalc spreadsheet. But you have to execute the script containing the function first. Autoloading a script that contains your favorite functions could be useful.
Recursion
A function can call itself (recursion). However the number of recursions is limited to about 500.
The following code will result in an error "[Error: Function recursion too deep]" after about 500 iterations:
function plusone(var) { var=var+1; print var; println; plusone(var); } plusone(0);
You can control the number of recursions, for example as follows:
function plusone(var) { var=var+1; print var; println; if (var<500) { plusone(var); } } plusone(0);
Or you can count the number of iterations using a global variable (see below for the Global variables function):
iterations=0; function plusone(var) { global(iterations); // make iterations global var=var+1; print var; println; iterations++; if (iterations>99) { return; } plusone(var); } plusone(0); print ("iterations ",iterations,"\n");
Return statement
A return statement ends a function and, optionally, returns a value.
function calcbmi(height,weight) { bmi=weight/square(height); return bmi; } mybmi = calcbmi(1.76,70); print ("My BMI is ",mybmi:1);
Forward declaration
A function can only call other functions that already have been defined. If you have more than one function, and they must call each other, you must forward-declare the function.
The following code results in an error because funcTwo is undefined when it is used in the body of funcOne.
function funcOne(var) { if (var>100) { return var; } return funcTwo(var*2); } function funcTwo(var) { return funcOne(var+1); } v=funcOne(1); ?v;
This problem is solved by a forward declaration of funcTwo, as follows:
function funcTwo(var); function funcOne(var) { if (var>100) { return var; } return funcTwo(var*2); } function funcTwo(var) { return funcOne(var+1); } v=funcOne(1); ?v;
Global variables function
The Global(variable1[,variable2) function marks the listed variables used in the function as global. These variables, when defined outside the function body, can also be used in the function; or when these values are defined in the function, they can also be used in the main body of the script.