This project has moved and is read-only. For the latest updates, please go here.

Possible to add a global function?

Jul 29, 2014 at 9:12 PM
Edited Jul 29, 2014 at 9:12 PM
Knowing that I can add global instances of host objects to the script engine like this:
engine.AddHostObject("random", new Random());
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 });
Does this sound reasonable? Is this possible?
Jul 29, 2014 at 9: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 10:04 PM
Awesome! You seem to have thought right about everything.