Just doing a quick check to make sure I understand this correctly due to a recent conversation.
I know in Godot you can indicate a var is private using underscore:
var _my_var: String = "hello"
and can also indicate functions as private
fun _my_function() -> void:
I know these don’t actually do anything in Godot, and are just used to signify to the programmer that vars and functions should not be used outside of the scope they’re declared in.
My question is, is there such a thing as private parameters/arguments?
fun my_function(_my_arg: String) -> void:
Surely the above here ^ is not a real thing? Primarily because using the underscore before a parameter/argument disables the unused parameter warning.
Furthermore, am I correct in assuming that declaring a parameter as private is sort of moot given that it’s already encapsulated and by the very nature of having been passed into a function sort of undermines the idea that it’s private?
Prefixing a function argument with an underscore tells Godot not to complain if that variable is unused in the function. If you don’t have warnings for that turned on, I don’t think it does anything.
Edit: Which you mentioned; I need more coffee.
The scope of function arguments is restricted to the function they’re in regardless of how they’re prefixed, so yeah, no effect.
It was my understanding that gdscript doesn’t have private and public members.
that said, the style guide recommends using underscore for properties and methods that are private:
underscores are used on built-in overridden functions like _ready() and _process(), but that’s just the name.
underscores in function parameters are used to get rid of the annoying unused variable warning, yes.
I think so, yes.
In C#, only classes can have private and public members. the compiler throws a nonsensical error 1513 (expected }) when trying to define a public variable within a Main function. other languages are like that too.
For the built in functions the _ prefix is not only cosmetic. The purpose is often to show that a function will get called automatically without you having to worry about it, or that you can only call them in some specific ways. For example you can not call _draw() by writing “_draw()” or by emitting custom signals connected to it, but you have to use queue_redraw() or emitting NOTIFICATION_DRAW.
I know since yesterday I struggled a bit with exactly this!
Edit:
I also think that by underscoring yourself, you are telling the engine to skip whatever is underscored and that perhaps it has some effect on performance.
Main thing is probably just convenience. Makes it easier to see something is local etc.