简体   繁体   中英

basic scripting language usable from C#

For a project, I require that my users are able to provide a simple function as a string, and I want to be able to evaluate it from my program. Let's say the function signature is always int f(int a, int b)

I want to make it so that my users can provide implementations of f written in a basic language. For instance:

return a*b;

if(a ==1) return b else return 3

And in my program, I want to be able to parse the user input function to make it a real callable function from my C# code. I only require basic features like basic math stuff and conditionals (not even loops).

Is there a basic "language" that exists that would allow me to interpret such functions defined as input and transform them in callable code? For instance I think that using Lua for this overkill?

Ideally I want something open-source, with minimal codebase and that is widely known to be of good quality. Does such a thing exist? Ideally it should also have implementations in several languages, like C# and Java. I know the temptation to write my own parser is high but I feel like there must be an out-of-the-box solution for my problem

If you only need math functions you can just have take in a string an eval it in a data table then return the results.

using System.Data;

//string mathExp = "3 * (2+4)"
public string ShiestyEval(string mathExp)
{
    DataTable dt = new DataTable();
    var v = dt.Compute(mathExp,"");
    return v;
}

To get it to be callable from your application, you need to provide an interface in which they can eval there methods, or if you wanna do some shady hack and generate an assembly though Il, and load it you can, it's a little vague on how you want to use it

you can also checkout JSharp

I don't think there is a simple way to do it. But there are some solutions that are easy to use. I really like Irony had a lot of fun with it. But it's a bit abandoned. You can use ANTLR but this one is not simple. You might be able to use Roslyn Api to do what you want it all depends. I am not sure how good of a sandbox do you need but you can use C# scripts This will allow you to do something like this

ScriptState state = CSharpScript.Run("int Times(int x) { return x * x; }");
var fn = state.CreateDelegate>("Times");
var value = fn(5);
Console.Write(value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM