I’m creating an API for non-programmers to write third-party code for a virtual multiplayer battlebot arena. The syntax for using globals would be nice:
function Step() {
if (sensor.wall) {
movement.brake();
movement.turnLeft();
}
if (sensor.enemy) {
movement.shoot()
}
if (movement.speed < 1) {
movement.accelerate(.1);
}
}
Globals in the above example would be sensor and movement. The script writer doesn’t care where they come from, just that they’re accessible. (No, this isn’t the final syntax. Just prototyping here.)
Scripts would be run on both the client (a browser) and server (via Node or Spidermonkey).
So, how to do this? It seems like my options are:
- Set all the globals lexically then
eval()the script (but that’s bad, right?) - Set all globals in the global scope and then run the script normally (but what about DOM globals, like
window?)
I could probably secure the global scope using Google Caja. I’d also like this to be performant since lots of Step() functions will be run per second on the same server.
Since the user scripts are received as text and I don’t care about bolting down access to
document,window, etc., (it’s a private application),eval()ing is the best option.