JOY Script is simple framework for creating simple scripting engines
It is to be used whenever developer needs to have part of application functionality scripted rather than hardcoded. For example author of game might want to script its game logic rather than hardcode everything.
Developer starts by writing set of instructions he needs in his scripting language: He creates set of classes by extending Instruction class from JOY Script. To use theese new instructions in script, he only needs to add package where this class is located to scripting engine and then use this class in script - with tag name derived from class name and attributes derived from setter methods.
Then, at runtime XML is parsed and instruction are instantiated. Instantiated script is added to library from which it can be retrieved and ran at any time.
To run script, developer retrieves script from library and passes it context in which script should run, and executes it.
This is example of how instructions are built, here is core instruction "log"
package cz.zweistein.joyscript.instruction.instructionset;
import cz.zweistein.joyscript.SerializationTool;
/**
*
* Logs information at info level
*
* @author prokop
*
*/
public class InstructionLog extends Instruction {
private String message;
@Override
protected void execute() {
logger.info(this.message);
}
@Override
public String getText(int level) {
return SerializationTool.indent(level) +"Log: "+this.message+"\n";
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Instruction cloneCode() {
InstructionLog instruction = new InstructionLog();
instruction.setMessage(this.message);
return instruction;
}
}
And here is its usage:
<scripts> <script id="demoScript1"> <log message="Hello, World!" /> </script> </scripts>
And this is code used to run this script:
GlobalContext globalContext = new GlobalContext();
Library library = new Library();
library.initScripts("xml/scripts.xml", new ArrayList<String>());
library.setGlobalContext(globalContext);
library.getScripts().getItem("demoScript1").getInstruction().run();
We initialize our own class path manually ListsubClassPath = new ArrayList (); subClassPath.add("org.example.ourinstructions");
We create our global context GlobalContext globalContext = new GlobalContext();
We load scripts to library
Library library = new Library();
library.initScripts("xml/scripts.xml", subClassPath);
library.setGlobalContext(globalContext)Get our script, run it, voala!
Script script = library.getScripts().getItem("script");
script.run();