Expression Parser - Evaluate Mathematical Expressions With Unity
Making games require a lot of balancing and math calculations. Sometimes you want to save a function into remote config and change it on the fly for flexible and easier testing.
I recently found out that Unity could do this. A small but helpful utility enables you to parse and evaluate mathematical expressions:
ExpressionParser https://wiki.unity3d.com/index.php/ExpressionParser
var parser = new ExpressionParser();
Expression exp = parser.EvaluateExpression("(5+3)*8^2-5*(-2)");
Debug.Log("Result: " + exp.Value); // prints: "Result: 522"
More than that, it could also turn your expression into a delegate and inject your custom function too. I found that quite amazing.
var sinFunc = exp2.ToDelegate("x");
Debug.Log("sin(90°): " + sinFunc(90)); // prints "sin(90°): 1"
parser.AddFunc("test", (p) => {
Debug.Log("TEST: " + p.Length);
return 42;
});
Debug.Log("Result: "+parser.Evaluate("2*test(1,5)")); /
Combine with a node-js server, we could use MathJs https://mathjs.org
let scope = {
a: 3,
b: 4
}
math.evaluate('a * b', scope) // 12
math.evaluate('c = 2.3 + 4.5', scope) // 6.8
Now, these two libraries will help you save your mathematical expression as a string config, evaluate it on both Unity client and Nodejs server.