How can I evaluate an expression string containing variables?

1.5k Views Asked by At

In Unity I'm trying to make it so you enter an expression and then it outputs a value but I want to use variables like:

x = 10
"x + x * 10"

^ outputs 200

2

There are 2 best solutions below

0
AudioBubble On

You will need to create a Mathematical expression evaluator. This is essentially an algorithm to tokenize your input string and then evaluate every single token. Just search for "Mathematical expression evaluator in c# " and you'll find what you need.Because this is a quite large project on its own, it might make sense to use a library for that. Here are some libraries:

Math-Expression-evaluator

Matheval

0
Olivier Duhart On

If you feel more adventurous you could even write your own évaluator using a parser library. This will allow specific behaviors if needed. Some libraries are :