Welp, I pulled it off!
The languages environment is complete sandboxed from everything, but inside its context you can teach it to have “NativeFunctions” that can access elements/methods inside the normal dom context (like window, fetch, babylon nodes etc). But before it gets passed back its sterilized so that no contextual leak happens.
Basically you define native methods like this:
and a user is able to do things like:
GetAllAssets()[0].position.x = 3;
This will allow scripting in runtime environments without causing security concerns.
here is the first script fully written and tested out:
const assets = GetAllAssets();
const asset = assets[0];
const speed = 1;
asset.position.x = 0;
function startBackForth(target){
OnAssetUpdateBeforeCamera(
asset,
()=>{
const delta = GetDeltaSeconds();
target.position.x = target.position.x + delta * speed;
(target.position.x <= 2.0);
},
()=>{
OnAssetUpdateBeforeCamera(
target,
()=>{
const delta = GetDeltaSeconds();
target.position.x = target.position.x - delta * speed;
(target.position.x >= 0 - 2);
},
()=>{
startBackForth(target);
}
);
}
);
}
startBackForth(asset);
I have not taught the interpreter about Unary Expressions yet (will do that soon) which us why -2 has to be defined as 0 - 2. It also does not care about return Expressions yet and just returns the last evaluated term in the function as the results.
Originally I did my own custom AST parser, but that is just overkill because libraries like acorn or seahorse handle things just fine. Next time if I had to do this id probably use s-evaluation instead of AST, but ehhh whatever. It would also be nice to have a call stack instead of recursive resolution. Ohh and to compile it to binary for extra speed… but this was my first go at a full fledged language and just having memberCalls/memberAssignments, classes, blocks, lambda functions etc makes it good enough to roll with for now. The idea was to keep it as close to JavaScript as possible but have complete control over the runtime evaluation.
I’m sure there are better ways to do this than make your own interpreter and some one will for sure have something to say about that, but you know what, I learned a lot, had a lot of fun and this is just the start so I am happy with the results.