Recovering function from input string

I am looking for a way how to allow user to input function and get it’s value at certain points. Lets say I have:

public string independentArgument = "x";
public string myFunction = "x*x";

public float x = 3.1f;
public float y;

void Start(){
    y = GetValue( independentArgument, myFunction, x );

float GetValue(string s1, string s2, float f1){
    float f2;

    return f2

The question here is how to “search” myFunction string to build up expression for y calculation?

If I understand what you’re saying, it’s a pretty complex topic. (Parsing) First you decide upon the rules by which the user can enter their string o’ commands, operators, variables, then code a solution which analyzes a string, breaking those components into individual commands, operators, and variables to create a sensible operation. Research parsing, string analysis, and regular expressions. Probably’ll need to use hashtables also for passing around your freshly parsed elements.

I’ve written a very simple expression parser some time ago. I just posted it on the wiki (ExpressionParser). It also allows you to specify custom functions. It works entirely on double values. It supports most functions from the System.Math class.

Simple example of how to add a custom method:

var parser = new ExpressionParser();
// add fibonacci function. Takes zero based index
parser.AddFunc("fib", (p) =>{
    double V1 = 1;
    double V2 = 0;
    int count = (int)p.FirstOrDefault();
    for(int i = 0; i < count; i++)
        double V = V1 + V2;
        V2 = V1;
        V1 = V;
    return V1;

var f = parser.EvaluateExpression("fib(x)").ToDelegate("x");
for (int i = 0; i < 20; i++ )
    Debug.Log("("+i+")" + f(i));

Since i haven’t tested the parser in Unity it had some errors due to .NET / Mono incompatibilities. I’ve fixed those (small) errors and created an example:

ExpressionParserTest(requires webplayer)

I’ve added links to the parser and the script for this demo below the webplayer. The scene just contains a camera with the ExpressionParserTest.cs attached.

Some notes on the demo:

  • all unknown parameters are simply fed with the same “x”-value
  • the x value goes from -100 to +100 with a step size of 0.1 So it calculates 2000 values each time it’s drawn.
  • The time “constant” is simple Unity’s Time.time.
  • I’ve added a “repeat” and “pingpong” function which works the same as Unity’s
  • The visible screen area goes from -100 to 100 in x and -50 to 50 in y