Godot Version
4.4beta1
Question
im trying to run gdscript given by the developer at runtime for a command-console type of thing for debugging/testing purposes. I take the input and give it to this function:
func eval_command_input(Str : String) -> String:
var Source := FileAccess.get_file_as_string("res://console.gd")
print("loaded console source : \n" + Source)
var CodeBlock := "#codeblock"
var BlockIdx := Source.find(CodeBlock)
var SourceStart := Source.substr(0, BlockIdx)
var SourceEnd := Source.substr(BlockIdx + CodeBlock.length(), -1)
var Command := SourceStart + Str + SourceEnd
print("updated console source : \n" + Command)
var ScriptRes := GDScript.new()
ScriptRes.source_code = Command
var Err := ScriptRes.reload()
if(Err != Error.OK):
var Msg := "Failed to evaluate '" + Str + "': " + error_string(Err)
push_warning(Msg)
return Msg
var Console := Node.new()
Console.set_script(ScriptRes)
self.add_child(Console)
Console.queue_free()
return Console.Returned
the console script is
extends Node
var Returned := String()
func _enter_tree() -> void:
#codeblock
return
the plan is to add functions and other variables it sets at the _enter_tree() call for the command to use. it actually works too (which im happy with) as if i give it the command “print(“hello!”)” everything works and it prints to the editor console. however, if i make a mistake or give it a garbage input, it fails on this line:
var Err := ScriptRes.reload()
to my understanding, if the script is invalid or has an error it the reload() call should just return a valid error code right? but when i do that, it halts the game and the stack trace gives me the error: “Parser Error: Identifier “asdjkfhaksdjhf” not declared in the current scope.”. wouldnt that parsing error come up when i call reload? or is there some other method of evaluating if a script is valid?