The function keyword begins definition of the user-function.
User-definable functions allow to encapsulate user code into easy-to-use modules that can be user in many places without need to copy the same code over and over again.
Functions must have a definition. The function definition includes the function body — the code that executes when the function is called.
A function definition establishes the name, and attributes (or parameters) of a function. A function definition must precede the call to the function. The definition starts with function keyword then follows function name, opening parenthesis then optional list of arguments and closing parenthesis. Later comes function body enclosed in curly braces.
A function call passes execution control from the calling function to the called function. The arguments, if any, are passed by value to the called function. Execution of a return statement in the called function returns control and possibly a value to the calling function.
If the function does not consist of any return statement (does not return anything) then we call it a procedure.
Following is an example of function definition:
//
the following function is 2nd order smoother
function IIR2(
input, f0, f1, f2 )
{
result[ 0 ]
= input[ 0 ];
result[ 1 ]
= input[ 1 ];
for(
i = 2; i < BarCount;
i++ )
{
result[ i ] = f0 * input[ i ] +
f1
* result[ i - 1 ] +
f2
* result[ i - 2 ];
}
return result;
}
Plot( Close, "Price", colorBlack, styleCandle );
Plot( IIR2( Close, 0.2, 1.4,
-0.6 ), "function
example", colorRed );
In this code IIR2 is a user-defined function. input, f0, f1, f2 are
formal parameters of the functions.
At the time of function call the values of arguments are passed in these variables.
Formal parameters behave like local variables.
Later we have result and i which are local variables. Local variables
are visible inside function only. If any other function uses the same variable
name they won't interfere between each other.