Run Initialization Code when a Script is Loaded

864 Views Asked by At

I have a GDScript file, and I would like to be able to run a block of code whenever the script is loaded. I know _init will run whenever an instance is constructed and _ready will run when it's added to the scene tree. I want to run code before either of those events happens; when the preload or load that brings it into memory first happens.

In Java, this would be a static initializer block, like so

public class Example {
    public static ArrayList<Integer> example = new ArrayList<Integer>;
    static {
        // Pretend this is a complicated algorithm to compute the example array ...
        example.add(1);
        example.add(2);
        example.add(3);
    }
}

I want to do the same thing with a GDScript file in Godot, where some top-level constant or other configuration data is calculated when the script is first loaded, something like (I realize this is not valid GDScript)

extends Node
class_name Example

const EXAMPLE = []

static:
    EXAMPLE.push_back(1)
    EXAMPLE.push_back(2)
    EXAMPLE.push_back(3)

Is there some way to get a feature like this or even to approximate it?

Background Information: The reason I care (aside from a general academic interest in problems like these) is that I'm working on a scripting language that uses GDScript as a compile target, and in my language there are certain initialization and registration procedures that need to happen to keep my language's runtime happy, and this needs to happen whenever a new script from my language is loaded.

In reality the thing I want to do is basically going to be

static:
    MyLanguageRuntime.register_class_file(this_file, ...)

where MyLanguageRuntime is a singleton node that exists at the top of the scene tree to keep everything running smoothly.

0

There are 0 best solutions below