Private vars inside custom godot script class

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tybobobo
:warning: Old Version Published before Godot 3 was released.

Is there a way to prevent direct access to a var that is inside an instanced custom script/class?

var someclassthatshouldnotbeaccess = “420”

print(classvar.someclassthatshouldnotbeaccess) <— Should not work, but I have no way to prevent it (as far as I know)

:bust_in_silhouette: Reply From: Bojidar Marinov

You can do it using setters/getters, like so:

var my_good_private_x = 6 setget private_gs,private_gs
var my_better_private_y = 9 setget private_gs,private_gs

func private_gs(val = null): 
    # Using a default value to make it possible to call with both 1 and 0 arguments (e.g. both as setter and getter)
    print("Access to private variable!!!")
    print_stack()
    pass # No set, no get for you!

# Usage:
func _ready():
    my_good_private_x = 54 # works!
    print(my_good_private_x) # 54
    self.my_better_private_y = 23 # migth work, depends on which version of godot you use

Yeah, that’s because when accessed in the the class itself through implicit scope, accessing the variable won’t use the getter and setter, right?
Anyways I prefer using prefixes, because it’s less boilerplate, slightly faster and it’s usually known that writing thing._priv is wrong :stuck_out_tongue:
Also, if this way of using setget is always the same, I wonder why we wouldn’t get a private keyword?

Zylann | 2016-09-15 12:45

@Zylann - you won’t get the keyword, since there is no issue on GH about it, so nobody knows if it is requested :wink:

Bojidar Marinov | 2016-09-15 12:50

As good as you can get it at this point. I hope to see a simpler “private” and perhaps “protected” types in the future :slight_smile:

Ended up adding _ in front of vars to indicate that they are supposed to be private

Tybobobo | 2016-09-15 12:56