this post was submitted on 25 Apr 2024
21 points (95.7% liked)

Godot

6007 readers
19 users here now

Welcome to the programming.dev Godot community!

This is a place where you can discuss about anything relating to the Godot game engine. Feel free to ask questions, post tutorials, show off your godot game, etc.

Make sure to follow the Godot CoC while chatting

We have a matrix room that can be used for chatting with other members of the community here

Links

Other Communities

Rules

We have a four strike system in this community where you get warned the first time you break a rule, then given a week ban, then given a year ban, then a permanent ban. Certain actions may bypass this and go straight to permanent ban if severe enough and done with malicious intent

Wormhole

!roguelikedev@programming.dev

Credits

founded 2 years ago
MODERATORS
 

Is there any way to run a given string at runtime? I have tried to write something like this by creating a new node and attaching a new script to it, and I have gotten this far:

var new_node:Node = Node.new()
add_child(new_node)
var new_script:GDScript = GDScript.new()
new_script.source_code = "extends Node\nfunc run():\n\t" + script_to_execute
print(new_script.source_code)
new_node.set_script(new_script)
pressed.connect(new_node.call.bind("run"))

This gets an error (but not a crash) when hitting that last line:

emit_signalp: Error calling from signal 'pressed' to callable: 'Node::call': Method not found.

This is pretty weird, as a Node should always have access to the method "call". Does someone have an idea on how to solve this / their own idea on how to implement runtime code editing and executing?

you are viewing a single comment's thread
view the rest of the comments
[–] sus@programming.dev 12 points 8 months ago* (last edited 8 months ago)

found a few examples of how to do it on a github issue:

var script = GDScript.new()
script.source_code = "func say_hello():\n\tprint(\"Hello!\")"
script.reload()
var script_instance = script.new()
script_instance.call("say_hello")

var MyClass = load("myclass.gd")
var instance = MyClass.new()
assert(instance.get_script() == MyClass)