Why func get() not work with local variable?

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

I will show an example.

func _ready():
	var variable = 123
    print(get("variable"))

output: Null
If the variable is global, then everything works.

var variable = 123
func _ready():
    print(get("variable"))

output: 123

How to access a local variable using the get function?

:bust_in_silhouette: Reply From: Zylann

A local variable only exists on the stack, when the function gets executed. Its lifetime is limited to the block in which it is declared, it’s not part of the object itself and it won’t persist outside of the function.
get only works for variables that are part of the object, those you declare outside of functions.

If you want to get the content of a local variable, you can only do it from within the function it was declared in, like this:

func _ready():
    var variable = 123
    print(variable))

But if you want the variable to stay in memory after the function is executed, it should be a member variable declared outside of the function, and it will be accessible by writing something like this:

# From within another script
var other = get_node("Path/To/Your/First/Node")
print(other.variable)

Or

print(other.get("variable")