Dynamic code

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Alexandr

hello, is it possible to make the code from the string be activated?
var s = “variable + = 1”
dynamic (s)

var variable = 10
var s = “print(variable)”
** output **

like that

:bust_in_silhouette: Reply From: flurick

Yes! https://twitter.com/reduzio/status/1027293084844019713

var e = Expression.new()
e.parse( "1+2")

Wow you ninja’d me! I’ve heard about this feature but I didn’t think it has been implemented.

Xrayez | 2018-10-16 18:41

This work in 3.0.6?

Alexandr | 2018-10-16 19:01

This works in 3.1 alpha at least.

Xrayez | 2018-10-17 08:00

: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():
	return variable
""" \
% [variable, p_expression] 
	# ^ use format string to substitute variables in a script
	# Should reload the script with changed source code
	# Need to create an instance of the script to call its methods
	var instance = Reference.new()
	# 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.