This project has moved. For the latest updates, please go here.

Possible to add a global function?

Jul 29, 2014 at 8:12 PM
Edited Jul 29, 2014 at 8:12 PM
Knowing that I can add global instances of host objects to the script engine like this:
engine.AddHostObject("random", new Random());
engine.Execute("Console.WriteLine(random.NextDouble())");
I wonder whether it would be possible to directly introduce global functions to the script engine so that I could directly execute this function in my script without specifying an object.

E.g. something like:
engine.AddHostFunction("add", delegate(int a, int b) { return a + b });
engine.Execute("Console.WriteLine(add(1,2))");
Does this sound reasonable? Is this possible?
Coordinator
Jul 29, 2014 at 8:35 PM
Hello UweKeim,

Yes, this is possible. Simply add an object of a delegate type:
engine.AddHostObject("add", new Func<int, int, int>(delegate(int a, int b) { return a + b; }));
You can also use a lambda expression to accomplish the same thing:
engine.AddHostObject("add", new Func<int, int, int>((a, b) => a + b));
Good luck!
Marked as answer by UweKeim on 7/29/2014 at 10:53 PM
Jul 29, 2014 at 9:04 PM
Awesome! You seem to have thought right about everything.