sklose / NCalc2

expression evaluator for .NET with built-in compiler
MIT License
170 stars 58 forks source link

Please allow bracket in parameter name #25

Open Thaina opened 5 years ago

Thaina commented 5 years ago

I wish I could write parameter name with bracket like this

var array = new float[] { 1,2,3,4,5,6 };
var e = new Expression("1 + (2 * [array[0]])");
e.EvaluateParameter += delegate(string name, ParameterArgs args) {
      // got "array[0]" as name
      if (name.StartsWith("array[") && name.EndsWith("]"))
      {
          int i = int.Parse(name.Replace("array[","").Replace("]",""));
          args.Result = array[i];
      }
};

If possible I would like to have it allow arbitrary nested bracket

var keys = new string[] { key0,key1,key2 };
var dict = new Dictionary<string,float>();
var e = new Expression("1 + (2 * [dict[key[0]]])");
e.EvaluateParameter += delegate(string name, ParameterArgs args) {
      // got "dict[key[0]]" as name for doing lookup
};
Thaina commented 5 years ago

@sklose

Will changing this

https://github.com/sklose/NCalc2/blob/19359d63fbd0bfde956ec95bf5db1aca02627bd5/grammer/NCalc.g#L265-L268

To this

NAME    :   '[' ( (options {greedy=false;} : ~('[' | ']')*) NAME* )* ']'
    ;

Did the job?

Thaina commented 5 years ago

Today I have clone your repo and change it to antlr4

This rule work for me

NAME    :   '[' (~('[' | ']') | NAME)*? ']'
    ;

If you interest https://github.com/Thaina/NCalc2

Bykiev commented 7 months ago

@Thaina, I believe it'll be better to use EvaluateOptions.IterateParameters like this:

https://github.com/sklose/NCalc2/blob/f8e42df6dbdb713cfb401063059b5d7d9d32b622/test/NCalc.Tests/Fixtures.cs#L655-L664