Skip to content

Script Hooks

Thomas Cashman edited this page Jul 9, 2016 · 1 revision

There are several methods available to interact with scripts from the game thread and to listen to script events.

Skipping a currently executing script

It is possible to skip a script during execution. An example of using this would be if your scripts are used for cutscenes and you want to allow the player to skip a scene.

int scriptId = scriptingEngine.compileScript("println \"Hello world!\"");
scriptingEngine.invokeCompiledScript(scriptId, scriptBindings, scriptListener);

...

scriptingEngine.skipScript(scriptId);

Skipping a currently executing GameFuture

It is also possible to skip a GameFuture. The GameFuture class provides a skipFuture() method to allow the future to be skipped. This in turn will call the onFutureSkipped() method of the same instance.

Listening for script events

You can receive a callback for when a script finishes successfully, is skipped or if an exception occurs using a ScriptInvocationListener. It is also possible to retrieve values of variables from your scripts when they have completed successfully.

First implement your ScriptInvocationListener.

public class MyScriptListener implements ScriptInvocationListener {
	@Override
	public void onScriptSuccess(int scriptId, ScriptExecutionResult executionResult) {
		//executionResult will contain all the variables from the script
		System.out.println(scriptId + " completed successfully");
	}
		
	@Override
	public void onScriptSkipped(int scriptId) {
		System.out.println(scriptId + " was skipped");
	}
			
	@Override
	public void onScriptException(int scriptId, Exception e) {
		e.printStackTrace();
		System.out.println(scriptId + " exception occurred");
	}
			
	@Override
	public boolean callOnGameThread() {
		//Change to false if you want the callbacks invoked on the scripting thread pool
		return true;
	}
}

Then, when you invoke your scripts pass your listener as an argument.

MyScriptListener scriptListener = new MyScriptListener();
ScriptBindings scriptBindings = new ScriptBindings();

scriptingEngine.invokeScript("println \"Hello world!\"", scriptBindings, scriptListener);

int scriptId = scriptingEngine.compileScript("println \"Hello world!\"");
scriptingEngine.invokeCompiledScript(scriptId, scriptBindings, scriptListener);