For people like me, it can be very confusing to have a variable not be specified by type.
Gladly, Godot contains ways of specifying scripts and variables by type, and I will show you how.
Assigning Type to Variables
var Name
That is still vague about what kind of variable that is, beside Name implies that a string
will be there, which might not be the case.
Beside, can be set a string value to it.
var Name = ""
Hm, yeah, there's a string there, but still not enough to specify what kind of variable that is.
I mean, you can place a number there or something, and it will still be okay for Name variable.
That's why you can add specification right after the variable name, to tell which kind of
value it will take.
var Name : String = ""
There, now that variable is bound to receive only String type variables. It's not necessary to assign a default value, by the way.
Specifying variable type on method arguments.
For methods like the one bellow, it's not much of a problem.
func Sum(a, b):
print_debug(str(a + b))
pass
func Sum(a: int, b: int):
print_debug(str(a + b))
pass
The specification can be used for types and also object types.
The method above doesn't seems very functional, though. The method does the sum, but
instead of returning a value, it prints a message on the log with the result of the sum.
Lets add a return type to it.
func Sum(a: int, b: int) -> int:
return a + b
There, now the method will return a integer variable, which will be the sum of a and b.
Do notice that pass is not the same as return, by the way. I discovered that after many bugs.
Assigning Classes to Script
Normally, a method will not know what type of the value its arguments is calling,
class_name NameOfClass
That's about it, and you can name the class anything you want, but probably
there's some rules regarding that, though.
Now you can find out if an object is of that class type...
if (value is NameOfClass):
...Or specify if that value is of a certain class type...
var MyNameOfClass = value as NameOfClass
...Or even specifying variable types...
var MyNameOfClass : NameOfClass
...Or simply setting argument of methods, or even return values of their type.
func NameOfClassClub(newMember: NameOfClass) -> NameOfClass:
No comments:
Post a Comment