How to convert a dictionary value (a string) into an argument (code block)?

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

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!

:bust_in_silhouette: Reply From: golden_pangolin

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?

:bust_in_silhouette: Reply From: Wakatta

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

Thank you! Very useful function.

golden_pangolin | 2021-09-07 03:39