I'm looking for something like Godot's Expression class, but which is able to run an entire script, not just a single line. I don't need it to return anything, just compile and execute the code. Is there anything like this in Godot?

  • xyz replied to this.

    Any info in the right direction would be very much appreciated.

    Godot does not currently have such a feature, but you can implement something similar using GDNative. GDNative is a library of native modules that can be added to a Godot project. With GDNative, you can write custom C++ scripts for executing scripts.

    kitfox What actual problem are you hoping to solve with this?

    Just to correctly answer this question: Yes, it's possible to compile GDScript at runtime with the GDScript class.

    var script := GDScript.new()
    script.source_code = "var answer = 42"
    script.reload()
    var obj = script.new()
    print(obj.answer)

      Jummit That looks like it could be useful. Is there any way to pass in parameters, like in Expression's execute() method? Also, does this actually run the script? I don't see any obvious ways in the Script class to execute anything.

      • xyz replied to this.

        kitfox Also, does this actually run the script?

        It does. Otherwise print(obj.answer) wouldn't print 42 in Jummit 's example.
        You can define any method in the source string and call it via obj object as you normally would. obj is in fact an instance of the class the script source is declared to extend:

        func _ready():
        	var script = GDScript.new()
        	script.source_code = """
        extends Node3D
        func test():
        	print(self)
        """
        	script.reload()
        	var obj = script.new()
        	obj.test()