0 votes

I'm have trouble trying to convert a returned dictionary value into code.

My dictionary value returns as "(randi() % 11 + 2)" which is a string. Is there a simple way to convert this into code? Do I have to use a regexp to remove the quotations?

I've tried int() and it didn't work to generate a random number in the range listed above.

Thank you!

Godot version 3.3.2
in Engine by (16 points)

2 Answers

0 votes

Found this function that works perfectly.

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

From another answer here...
Does GDScript have a method to execute a string of code?

by (16 points)
0 votes

You can use the call() or callv functions but first your dictionary value is in bad format. You can either slice your string or rearrange it in a way to be compatible with those functions

# this assumes no encapsulation of ( )
var callv("randi() % 11 + 2".split("()")
by (4,636 points)

Thank you! Very useful function.

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.