Dynamic code

:bust_in_silhouette: Reply From: Xrayez

You can create scripts dynamically. I scratched my head a bit and figured this silly example, but should give you an idea:

extends Node2D

var variable = 0

func _ready():
	var expression = "variable += 1"
	var result = execute(expression)
	
	print(result) # should print 1
	
	
func execute(p_expression):
	assert(typeof(p_expression) == TYPE_STRING)
	
	# Create a new script with embedded expression
	var script = GDScript.new()
	
	# Define source code needed for evaluation (extends Reference by default)
	script.source_code += \
"""
var variable = %s

func eval():
	%s
	return variable
""" \
% [variable, p_expression] 
	# ^ use format string to substitute variables in a script
	
	# Should reload the script with changed source code
	script.reload()
	
	# Need to create an instance of the script to call its methods
	var instance = Reference.new()
	instance.set_script(script)
	
	# Evaluate expression here
	var result = instance.call("eval")
	
	return result
	

Another thing you would do it is to write a custom GDScript parser in GDScript to evalulate strings on the fly!

EDIT: flurick’s answers your question by using a specialized Expression class.