Skip to content
nilproject edited this page Nov 18, 2014 · 19 revisions

Samples

Declaring global variable

C#

NiL.JS.Core.Context.GlobalContext.DefineVariable("flag").Assign(true);

JavaScript

console.log(flag); // true

console.log(typeof flag); // boolean

Declaring global function

C#

NiL.JS.Core.Context.GlobalContext.DefineVariable("alert").Assign(new ExternalFunction((thisBind, arguments) => {

System.Windows.Forms.MessageBox.Show(arguments[0].ToString());

return JSObject.Undefined; // or null

}));

JavaScript

alert("Hello!");

Call JS-function from C#

C#

var script = new Script("function message(){ return 'Hello, world!'; }");

var messageFn = script.Context.GetVariable("message").Value as NiL.JS.Core.BaseTypes.Function;

System.Windows.Forms.MessageBox.Show(messageFn.Invoke(null).ToString());

With parameters

var script = new Script("function add(a, b){ return a + b; }");

var addFn = script.Context.GetVariable("add").Value as NiL.JS.Core.BaseTypes.Function;

System.Windows.Forms.MessageBox.Show(addFn.Invoke(new NiL.JS.Core.Arguments { 1, 2 }).ToString());

Access to fields

C#

var script = new Script("function wrap(value){ return { value : value }; }");

var wrapFn = script.Context.GetVariable("wrap").Value as NiL.JS.Core.BaseTypes.Function;

System.Windows.Forms.MessageBox.Show(wrapFn.Invoke(new NiL.JS.Core.Arguments { "Hello" }).GetMember("value").ToString());

Proxy native object to JS-environment

As parameter

C#

var script = new Script("function unwrap(value){ return value.Value; }"); // Fields, Properties, Methods and Events are available directly, without extra syntax

var wrapFn = script.Context.GetVariable("unwrap").Value as NiL.JS.Core.BaseTypes.Function;

System.Windows.Forms.MessageBox.Show(wrapFn.Invoke(new NiL.JS.Core.Arguments { NiL.JS.Core.TypeProxing.TypeProxy.Proxy(new { Value = "Hello" }) }).ToString());

As constructor

C#

var script = new Script("Form().ShowDialog()");

script.Context.AttachModule(typeof(System.Windows.Forms.Form));

script.Invoke();

C#

var script = new Script("Console.WriteLine('Hello')"); // Static members available too

script.Context.AttachModule(typeof(System.Console));

script.Invoke();

Array

C#

var script = new Script(@"function add(array){

var res = 0;

for (var i = array.Length; i--;) res += array.Get(i);

return res;

}");

var addFn = script.Context.GetVariable("add").Value as NiL.JS.Core.BaseTypes.Function;

System.Windows.Forms.MessageBox.Show(wrapFn.Invoke(new NiL.JS.Core.Arguments { NiL.JS.Core.TypeProxing.TypeProxy.Proxy(new[]{1,2,3,4}) }).ToString());

Clone this wiki locally