Function can be created at run-time and added into execution scope by compiling a string containing its definition. Aside this, there are few other possibilities to introduce functions to script. Function could be native - compiled from source, or external - is .NET object implementing IInvokable interface.
Simple Definition
function NAME (id1, id2, ... , idn)
{
Statement
}
With references to global variables
function NAME (id1, id2, ... , idn) global(id1,...,idk)
{
Statement
}
For example:
y = 100;
function f() global(y)
{
y = y - 1;
}
f();
After executing this script the variable y will have its value 99.
With contracts
function (id1, id2, ... , idn)
[
pre(boolExpr);
post(boolExpr);
invariant(boolExpr);
]
{
Statement
}
By function expression (this is usually called anonymous function)
NAME = function (id1, id2, ... , idn) { Statement };
For example:
helloFunction = function (name) { return string.Format("Hello {0}!", name);};
helloFunction('John');
All examples of syntactic function definitions are equal to the function expression. In fact when function a() {...} is written it actually executes as following assignment statement:
a = function () {};
By default after compilation all function expressions will be executed, so corresponding variables will appear in script scope. This is done by FunctionDeclarationVisitor post processing available in the library.
Note: The functional expression:
function (params) { body };
evaluates to an IInvokable object. During the execution of the function a local scope (Contract Scope) is created and all variables created within this scope will be removed at function return;
Example showing various ways of invoking function:
function fac(n){
if (n==1) return 1;
else return n*fac(n-1);
}
rez = fac(5);
//pointer to a function
Func_pointer = fac;
Func_pointer(4); //Call function using pointer
//Anonymous function
aFunction = function(n){
if (n==1) return 1;
else return n*aFunction(n-1);
};
//Call function created as assignment
aFunction(5);
//Using .NET Method
sin = Math.Sin;
v = sin(0.75);
See also: