Efficient way to run multiple scripts using javax.script -
i developing game i'd have multiple scripts implement same structure. each script need run in own scope code doesn't overlap other scripts. example:
structure.js
function oninit() { // define resources load, collision vars, etc. } function onloop() { // every loop } function clickevent() { // clicked me } // other fun functions now, lets have: "badguy.js", "reallyreallybadguy.js", "otherbadguy.js" - above in terms of structure. within game whenever event takes place, i'd invoke appropriate function.
the problem comes down efficiency , speed. found working solution creating engine each script instance (using getenginebyname), doesn't seem ideal me.
if there isn't better solution, i'll resort each script having own unique class / function names. i.e.
badguy.js
var badguy = new object(); badguy.clickevent = function() { }
i don't think need create new scriptengine every "guy". can manage them in 1 engine. advance apologies butchering game scenario.....
- get 1 instance of rhino engine.
- issue eval(script) statements add new js objects engine, along different behaviours (or functions) want these objects support.
- you have couple of different choices invoking against each one, long each "guy" has unique name, can reference them name , invoke named method against it.
- for more performance sensitive operations (perhaps sort of round based event loop) can precompile script in same engine can executed without having re-evaluate source.
here's sample wrote in groovy.
import javax.script.*; sem = new scriptenginemanager(); engine = sem.getenginebyextension("js"); engine.getbindings(scriptcontext.engine_scope).put("out", system.out); eventloop = "for(guy in allguys) { out.println(allguys[guy].action(action)); }; " engine.eval("var allguys = []"); engine.eval("var badguy = new object(); allguys.push(badguy); badguy.clickevent = function() { return 'i badguy' }; badguy.action = function(activity) { return 'i doing ' + activity + ' in bad way' }"); engine.eval("var goodguy = new object(); allguys.push(goodguy); goodguy.clickevent = function() { return 'i goodguy' }; goodguy.action = function(activity) { return 'i doing ' + activity + ' in way' }"); compiledscript executeevents = engine.compile(eventloop); println engine.invokemethod(engine.get("badguy"), "clickevent"); println engine.invokemethod(engine.get("goodguy"), "clickevent"); engine.getbindings(scriptcontext.engine_scope).put("action", "knitting"); executeevents.eval();
Comments
Post a Comment