+9 votes

/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)

in Engine by (24 points)
edited by

3 Answers

+5 votes
Best answer

This is the closest thing I could think of...

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
by (488 points)
selected by
Yup, this works! Will share soon!
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.
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?

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
0 votes

I think you are talking about

OS.execute( String path, StringArray arguments, bool blocking, Array output=Array() )

Execute the binary file in given path, optionally blocking until it returns. A process ID is returned.

by (576 points)
I'm sorry I was not precise  enough in my question. I said I want to build a REPL, so I will detail it editing my question.
0 votes

Modern Godot has such functionality! Example of using Expression class doing exactly what you described!

by (18 points)

This does not answer the question as Expression is not a REPL, it is a math-focused expression parser that never touches the language shell.

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 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.