NeilFraser / JS-Interpreter

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

How to work with custom scopes? #221

Closed niko-roether closed 2 years ago

niko-roether commented 2 years ago

Hi, all. For my project I'd like to create a hierarchical structure of custom scopes, in each of which certain variables are defined, and inside each of which I can execute new code at any time. I would like to be able to create and modify these scopes using the external API. I haven't been able to figure out a way to get this to work, so I decided to post a question here - is this possible? And if not, is there some way to get something similar to work?

Basically, my ideal scenario would be something like this:

const scope = interpreter.createSpecialScope(interpreter.globalScope);
interpreter.setValueToSpecificScope(scope, "someVariable", 34);
interpreter.appendCodeToScope(scope, "alert(someVariable)");
interpreter.runScope(scope);

I understand that this isn't really how the interpreter is set up, and I also thought about perhaps creating a new interpreter instance for each "scope" that I'm thinking of and inheriting variables manually, but because I'm pretty inexperienced using this library, I'm kind of stuck.

Basically, I would like to know if there is an intended way to do something similar to this, and if not, maybe some pointers as to how I could get it to work.

Thanks in advance!

niko-roether commented 2 years ago

Ok, so I basically ended up building my own system where every "scope" has his own Interpreter instance, and I transfer variables between them manually, as I already said.