+2 votes

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

in Engine by (121 points)

2 Answers

+6 votes
Best answer

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

var e = Expression.new()
e.parse( "1+2")
by (953 points)
selected by

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

This work in 3.0.6?

This works in 3.1 alpha at least.

+1 vote

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.

by (1,371 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.