For plugin developers - wytrem/exmachina GitHub Wiki

ExMachina Java API

Brief document about using the Java API.

Script references

A ScriptRef holds all the needed data to retrieve a script's source code. Script references are ConfigurationSerializable.

From the scripts/ folder

Use this method to reference a script stored in the scripts/ folder.

 // Will return a reference to the script located in plugins/ExMachina/scripts/example/some_script.js
ScriptRef.fromPath("example/some_script")

Inline script

Use this method to reference an "inlined" script: a script directly referenced by its source code.

ScriptRef.inline("print(\"Hi there! I'm an in-lined script\"")

Creating your own ScriptRef

You can implement your own ScriptRef, usually using the the Inline interface.

import net.wytrem.spigot.exmachina.refs.Inline;

@SerializableAs("script:stringprinter")
public class StringPrinter implements Inline {
    private final String theStringToPrint;

    public StringPrinter(String theStringToPrint) {
        this.theStringToPrint = theStringToPrint;
    }

    @Override
    public String getSource() {
        return "print(\"" + this.theStringToPrint + "\");";
    }
    
    // Serialization methods (see org.bukkit.configuration.ConfigurationSerializable)
    @Override
    public Map<String, Object> serialize() {
        return new HashMap<String, Object>() {{
            put("theStringToPrint", theStringToPrint);
        }};
    }

    public static StringPrinter valueOf(Map<String, Object> map) {
        return new StringPrinter(map.get("theStringToPrint").toString());
    }
}

Running a script

Once you got a ScriptRef, you can use it to run the referenced script:

// Retrive the ExMachina engine
ExMachina exMachina = ExMachina.get();

// Create a ScriptRef
ScriptRef ref = ScriptRef.inline("print(\"Hi there!\");");

try {
    // Run the script and get the result
    Object result = exMachina.eval(ref);
} catch (ScriptException e) {
    e.printStackTrace();
}

You can also use ExMachina#eval(ScriptRef, Map<String, Object>) or ExMachina#eval(ScriptRef, ScriptContext) to provide additional bindings or context.