JEP allows you to add custom functions by calling jep.FunTab.AddFunction(String
name, IPostfixMathCommand function)
. Custom functions are no different
from built-in functions, so you can use the source code of the built-in functions
as a template. The class methods are accessed both during parsing and evaluation.
During parsing, the parser needs to know how many parameters are allowed.
During evaluation, the Run(Stack<Object>)
method is called to perform the actual calculation.
The following is an example of how a custom function can be added.
Assume you want to add a function "Half" to divide a number by two (for demonstration purposes).
SingularSys.Jep.Functions
namespace). In this example we will name it "Half"numberOfParameters = 1;
numberOfParameters
value to -1. It is highly recommended to study the Sum.cs
code as an example
of a function that accepts any number of parameters. run(Stack<Object> inStack)
method. The parameters are passed in
a Stack object. This same stack is used as the output for the function.
So we first need to pop the parameter off the stack, calculate the result,
and finally pop the result back on the stack.
public override void Run(Stack<object> inStack) { // check the stack CheckStack(inStack); // get the parameter from the stack Object param = inStack.Pop(); // check whether the argument is of the right type if (param is JepDouble) { // calculate the result double r = ((JepDouble)param).DoubleValue / 2; // push the result on the inStack inStack.Push(new JepDouble(r)); } else { throw new EvaluationException("Invalid parameter type"); } }
jep.FunTab.AddFunction("half", new Half());
bool CheckNumberOfParameters(int n)
to catch an illegal number of arguments at parse time.Source files