Topic was automatically imported from the old Question2Answer platform.
Asked By
icarito
Old Version
Published before Godot 3 was released.
/me wants a REPL !
What is a REPL?
It’s a Read-eval-print loop
A read–eval–print loop, also known as an interactive toplevel or language shell, is a simple, interactive computer programming environment that takes single user inputs, evaluates them, and returns the result to the user; a program written in a REPL environment is executed piecewise. (from REPL at Wikipedia)
func evaluate(input):
var script = GDScript.new()
script.set_source_code("func eval():\n\treturn " + input)
script.reload()
var obj = Reference.new()
obj.set_script(script)
return obj.eval() # Supposing input is "23 + 2", returns 25
The script’s source code formatted looks like this:
func eval():
return # plus the input string
Yup, this works! Will share soon!
icarito | 2016-02-27 09:20
Keep in mind that you cannot achieve complete REPL with this approach though. Since the script cannot be reloaded when there are existing instances, you would not be able to do something like this.
neikeq | 2016-02-27 11:37
This works fine for concrete expressions (e.g. “23+2”), but I get errors anytime I try to evaluate an expression containing variables, likely due to scope issues. Is there any way to evaluate a string as an expression when that expression/string contains variables?
girard | 2016-03-02 10:54
The issue with variables is likely due to the fact that the provided answer does not include an appropriate extends keyword as a normal script would. If the object for instance was a Node2D then the script would need to include something like extends Node2D before the first func.
The generated eval code would then look like:
extends Node2D # changes to match object used with .set_script()
func eval():
return # plus the provided epilogue