How to create a variable that won't become negative

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

I created a global variable, but during the game I don’t want that the variable became negative. For now I do this:

If variable > 0
variable -= 1

But it is becoming boring to do with all the items and stuffs in game…

:bust_in_silhouette: Reply From: jgodfrey

You can create a setter function for the variable. In that function, you can pre-process the value before accepting, rejecting, or changing it.

So, for example, in your global script (Globals.gd in this case):

# set up the var and define a setter function
var pos_var = 1 setget pos_var_set

# here, only accept the value if it's positive. Otherwise, set it to zero.
func pos_var_set(new_val):
   if new_val > 0:
	   pos_var = new_val
   else:
	   pos_var = 0

Now, from some other script, you won’t be able to set the var to a negative value

func _ready():
	Globals.pos_var = 2
	print(Globals.pos_var)
	Globals.pos_var -= 10
	print(Globals.pos_var)
	Globals.pos_var = -100
	print(Globals.pos_var)

See the docs here for details: