codingseb / ExpressionEvaluator

A Simple Math and Pseudo C# Expression Evaluator in One C# File. Can also execute small C# like scripts
MIT License
595 stars 99 forks source link

Value accessor for context objects. #131

Closed Kinggrass closed 2 years ago

Kinggrass commented 2 years ago

Hi @codingseb,

I want to make a suggestion to you. I havent found another way, so I pointing it out falsly as a issue, apologizes for that.

I would like to ask if it would be possible for you to implement something how to access a information of the context over a solver/accessor which defines where the variables can be accessed. I would say it is more a suggestion, because it depends if you have time or find it useful yourself.

For Exampel:

ExpressionEvaluator evaluator = new ExpressionEvaluator();

evaluator.Context = new Class()
{
    aDictionary = new Dictionary<string, float>();
};

evaluator.Context.Accessor = (variableNameInExpressionToSubstitute, contextObject) => contextObject.aDictionary[variableNameToSubstitute];  

Which then uses the values which are provided over the accessor.

Thanks for reading my suggestion.

codingseb commented 2 years ago

Hi @Kinggrass.

Did you try on the fly events ? Some examples here

I don't know if it is what you want but with a bit more conditions you can do what you asked in your example.

ExpressionEvaluator evaluator = new ExpressionEvaluator();

evaluator.Context = new MyClass()
{
    aDictionary = new Dictionary<string, float>();
};

evaluator.PreEvaluateVariable += (sender, e) => 
{
    if (e.This == e.Evaluator.Context && e.This is MyClass myClass)
    {
        e.Value = myClass.aDictionary[e.Name];
    }
}
codingseb commented 2 years ago

e.This if not null is the object on which the property/field is called. e.Evaluator is the evaluator that is currently evaluating the expression. That could also be get with sender as ExpressionEvaluator e.Value can be set to return the corresponding value.

Kinggrass commented 2 years ago

HI, @codingseb, Thank you really much to point me there. It was not clear to me that I can access the context object via VariablePreEvaluationEventArg in this way.

Meanwhile, I made a regex that identifies the variables and then initializes them via evaluator.variables. But now I can change this fortunately.

Thanks for the hint.