Getting variables from a script (or source string)?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Adham
:warning: Old Version Published before Godot 3 was released.

I have a script’s source that I will need to extract variables from. I have to do it in this way due to an implementation detail. Here’s what I did:

var script = GDScript.new()
script.set_source_code('var test_var = "hi this is working"') 
var my_object = Node.new()
var my_object.set_script(script)

Then I do:

print(my_object.test_var) #I get an error! Doesn't work :(

Why doesn’t it work? What am I missing here? I tried using Reference.new() but still doesn’t work!

I can propose an alternative.
Load script like node.

Rihard | 2016-07-19 11:57

:bust_in_silhouette: Reply From: ericdl

Reload the script after setting it, and remove the second ‘var’ declaration on my_object:

var script = GDScript.new()
script.set_source_code('var test_var = "hi this is working"')
script.reload()
var my_object = Node.new()
my_object.set_script(script)
print(my_object.test_var)