Add setget onto existing variable from inherited class

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

I have a script that is extending the GridContainer, I am using the additional variable rows with appropriate setget applied, but I would like to use seget with the columns variable as well. Is it possible to add a setget onto an existing variable from an inherited class?

:bust_in_silhouette: Reply From: njamster

Is it possible to add a setget onto an existing variable from an inherited class?

No. However, you can override the virtual _set- and _get-methods that are called after the built-in setter is called to achieve something very similar:

func _set(property, value):
	if property == "columns":
		print("SET: columns)

func _get(property):
	if property == "columns":
		print("GET: columns")

If you want to change the value of columns in _set, things become a bit tricky though as calling set() leads to an endless loop crashing the engine. After toying around a little, I came up with the following solution for that:

var modified = []

func _set(property, value):
	if property in modified:
		modified.erase(property)
		return false

	if property == "columns":
		modified.append(property)
		set(property, value+2)
		return true

However, I cannot guarantee that this doesn’t has unwanted side-effects.

Also keep in mind that setter functions are not called locally unless prefixed by self:

func _ready():
    columns = 5        # will _not_ trigger the setter
    self.columns = 5   # will trigger the setter