Writing and interpreting GDScript in real time?

Godot Version

4.4 RC 1

Question

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.

Maybe Expressions is what you are looking for. Note that this has obvious security risks

If you just need to overwrite functionality based on a resource, you can change the attached script of a resource in the editor.

1 Like

Expressions are very limited, they don’t even allow creating new variables.

1 Like

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.

1 Like

Thank you, that seemed to have worked!

I have to ask something again though, something I asked some months ago but didn’t get an answer to:

Is it then possible to retrieve the errors from a script, or is that only possible within C?

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.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.