How would you write an 'eval'/'exec' function that could evaluate strings as expressions and handle variables?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By girard
:warning: Old Version Published before Godot 3 was released.

The code in the linked question can evaluate a string as an expression, but only a simple one using actual values. When I try any expression using a variable, I get an error, presumably because the new Reference is outside the scope of any variables elsewhere in my script.

SOLVED (kind of): Using Globals.set() and Globals.get() will let you access variables in the evaluated expression. It would be nice to be able to evaluate expressions with variables without having to use Globals, though.

girard | 2016-03-03 11:57

With minor modification it can get other nodes and run a multi-line script. I don’t think it is worth the hassle as you cannot step the scripts. It would be simpler if Godot exposed full scripting functionality to modders.

	#Example script:
	var commands = """
	var p = get_parent()
	p.attack("bob")
	p.set_stat("Strength", 4)
	p.set_quest("quest1", 1)
	if p.is_quest("quest1", 1):
		prints("it works!")
		p.ding_bat = 2
		return true
	return false
	"""

func run_script(input):
	var script = GDScript.new()
	script.set_source_code("func eval():" + input)
	script.reload()
	
	#var obj = Reference.new()
	var obj = Node.new() #So we can call get_node
	obj.set_script(script)
	add_child(obj)
	var ret_val = obj.eval()
	remove_child(obj)
	
	return ret_val

whooshfrosted | 2017-03-27 04:01

Modern Godot has Expression class

ntfshard | 2020-07-02 01:19

For those who want something closer to “eval” (not recommended, unless you know what you are doing), you have to start the script with “extends Node”.

Christian Baune | 2020-07-21 14:09

Modern Godot has Expression class

For future reference this is entirely incorrect, Expression does not evaluate in gdscript, its an independent math-focused expression parser.

Spartan322 | 2021-02-02 08:28