How to use setget keyword?

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

I want to write return functions

:bust_in_silhouette: Reply From: hilfazer

Both setter and getter:

var my_var setget my_var_set, my_var_get

func my_var_set(new_value):
    my_var = new_value

func my_var_get():
    return my_var # Getter must return a value.

Only a setter

var my_var = 5 setget myvar_set

Only a getter

var my_var = 5 setget ,myvar_get


:bust_in_silhouette: Reply From: SIsilicon

You use setgetwhen defining variables that are outside functions. The syntax is as follows.

var setter_and_getter setget setter, getter
var only_setter setget setter
var only_getter setget , getter

# Any initialization of a variable most be done before setget.
var setget_initialized = 0 setget setter, getter

The setter and getter are functions that you must define in the script. The simplest example of these two are as follows.

func setter(value):
     something = value

func getter():
     return something

The setter function is called whenever it’s corresponding variable gets set.
And the getter is called when said variable is accessed in anyway.

 #assuming something is from a different script
 something = 0 # setter gets called.
 var other = something # getter gets called.

They won’t be called however if the variable being manipulated is inside the same script it was defined.

 #assuming something is in the same script
 something = 0 # setter does not get called.
 self.something = 0 # doing this will make the setter get called.

From what I can see, the setter is also not called if the property is modified in a script that extends the script that declared the variable.

oskfo | 2019-05-01 15:44

this came up while searching so for anyone that encounters this, you have to change the property using the self keyword, e.g. self.something = 0, to trigger the setter from the parent.

decaprecated | 2021-06-30 00:36