I want to have the ability to convert a string with GDScript code in it and convert it to a GDScript resource (which extends Script, which extends Resource).
The .new() constructor however instantiates the script to the object it should contain, and doesn’t actually create a new instance of GDScript.
Is there some way i can kinda do this:
extends Node
var my_script := """extends Node
func get_some_data() -> String:
return "Hello World!"
"""
func _ready():
# Create new GDScript with the my_script code
var gdscript:GDScript = GDScript.new()
var gdscript.source_code = my_script
# creates a new node of that type and adds it to the tree
var script_instance:Node = gdscript.instantiate()
add_child(script_instance)
# Print the results of the script, Should be "Hello World"
var script_output:String = script_instance.get_some_data()
print("Script output: ", script_output)
This would be like - SUPER helpful for designing ingame tools and stuff.
EDIT: I am aware that I could store the GDScript as some my_script.gd file, then load() it and then instantiate it… but that feels like a hacky solution which might override some other files which are already present.
You must reload the script after editing it’s source.
var gdscript:GDScript = GDScript.new()
gdscript.source_code = my_script
var err := gdscript.reload()
assert(err == OK, "Couldn't compile script")
var script_instance = gdscript.new()
This isn’t sandboxed so the script has full access to your game’s internals and the operator’s computer. You may want to look into Lua plugins instead.
The specific line number/parser errors will be pushed to the output or stack trace, Godot does not have a way to catch those errors, they only return var err in my example which can assess failure.