How to create a "mirror" variable?

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

I would like to know how to create a variable that points to the same data as another variable, capturing its value automatically.

For example:

var a = 1
var b = mirror of a
a = 2
print(a) # 2
print(b) # 2

I know this applies to objects like Dictionary, but I would like to know about other data types.

I cannot think of any data type that does this, but you could create a function that updates two variables to have the same value. Would this work for you?

johnygames | 2019-12-31 14:52

To expand on this comment:

extends Node2D

var a: int = 0 setget set_a, get_a
var b: int = a setget , get_b

func set_a(value: int):
	a = value
	b = a

func get_a():
	return a

func get_b():
	return b

Just always go through the setters/getters for the variables.

2D||!2D | 2019-12-31 16:24

I’m pretty sure stuff does not work like that in GdScript for simple data types. Because what you want to do is have a pointer to your value instead of having it saved. In C++ you it would be straight forward, on the other hand, in GdScript, all that is handled by the interpreter and you can’t simply do it.
As a work around, you can create a class that holds a value, your int for example and use instances the class to access the values. This works because any instance of a class is a complex object, thus accessed by reference.

tastyshrimp | 2020-01-01 16:20