java-commons/muscript/README.md
JFronny 516fcea3a1
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
muScript: better documentation
2023-03-11 17:03:17 +01:00

2.7 KiB

μScript

μScript was created to allow respackopts pack authors to specify conditions for loading resources in a more human-friendly manner than the previous json tree-based system.

It is intended to be vaguely like java in its syntax, though it deviates in some aspects.

The language is parsed into an AST representation which is executed in-place, no compilation is performed. μScript supports outputting data using various types, not just strings or booleans.

The purpose of this document is to be a guide on embedding μScript in your application or library. For details on how to use the language, look here.

Embedding μScript

μScript is available as a maven package which you can add to your project. To use it, first parse an expression via Parser.parse(String script) and convert the returned generic expression to a typed one by calling as(Bool|String|Number|Dynamic)Expr. This process may throw a ParseException. You may also use Parser.parseScript(String script) for multi-expression scripts. You can call get(Dynamic<?> dataRoot) on the result to execute the script on the provided data, which should be a Scope which you created with StandardLib.createScope() to add standard methods. This is also where you can add custom data to be accessed by your script. The execution of a script can throw a LocationalException which may be converted to a LocationalError for printing using the source of the expression if available. You may also call StarScriptIngester.starScriptToMu() to generate μScript code from StarScript code.

A full example could look as follows:

public class Example {
    public static void main(String[] args) {
        String source = String.join(" ", args);
        Expr<?> parsed;
        try {
            parsed = Parser.parse(source); // or Parser.parse(StarScriptIngester.starScriptToMu(source))
        } catch (Parser.ParseException e) { // Could not parse
            System.err.println(e.error);
            return;
        }
        BoolExpr typed;
        try {
            typed = parsed.asBoolExpr();
        } catch (LocationalException e) {
            System.err.println(e.asPrintable(source));
            return;
        }
        Scope scope = StandardLib.createScope()
                .set("someValue", 15)
                .set("someOther", Map.of(
                        "subValue", DFinal.of(true)
                ));
        boolean result;
        try {
            result = typed.get(scope);
        } catch (LocationalException e) {
            System.err.println(e.asPrintable(source));
            return;
        }
        System.out.println("Result: " + result);
    }
}