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?
Can I compile and execute a script at runtime?
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.
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)
- Edited
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()