+2 votes

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)

in Engine by (476 points)

1 Answer

+2 votes
Best answer

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
by (1,566 points)
selected by

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 :p
Also, if this way of using setget is always the same, I wonder why we wouldn't get a private keyword?

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

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.