NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
2k stars 353 forks source link

What's returned when code returns non-primitives #144

Closed mercmobily closed 6 years ago

mercmobily commented 6 years ago

Hi,

All is well and easy when the code run by the interpreter is a sting or a number. However, when it's an object or an array, I am seeing weird results. For example:

var myInterpreter = new global.JSInterpreter.Interpreter(' r = {a:10 }) myInterpreter.run() typeof myInterpreter.value

The object's value is actually in myInterpreter.value.properties For arrays, things are even stranger.

Is this as intended?

mercmobily commented 6 years ago

At the moment, when I now that the function will return an Array and r is what came back, I am running:

r = Array.prototype.map.call(r, function (i) { return i.properties })

But surely...

cpcallen commented 6 years ago

JS Interpreter uses its own internal representation of objects. Obviously, since the interpreter is written in JavaScript, the interpreter objects are represented as one or more native JS objects, but the representation is not intended to be accessed directly by the caller.

Any native value passed in to the interpreter (e.g. as the value argument to Interpreter.prototype.setValueToScope) should first be converted to the internal representation using Interpreter.prototype.nativeToPseudo. Conversely, values being retrieved should be converted to native JS values using Interpreter.prototype.pseudoToNative.

So in this case what you want is more like this:

var myInterpreter = new Interpreter('r = {a: 10};')
myInterpreter.run()
var r = myInterpreter.pseudoToNative(myInterpreter.value);
mercmobily commented 6 years ago

Awesome thanks. Please see my comment on #144 where I offer to actually document these methods...