This is some interesting behavior I stumbled upon recently. Take the following code:
func foo() -> float:
return 1.0
func bar() -> bool:
return foo()
func _ready() -> void:
var b: bool = false
var i: int = 1
i = b
print(foo()) # prints 1.0
print(bar()) # prints true
print(i) # prints 0
print(b) # prints false
In this example I have functions and variables of a set type that are automatically casted to another type. I believe this could potentially be error-prone as in the case of the function bar() I should return a boolean but instead I return a float, so GDScript makes the conversion from float to bool with no warning. Same goes for assigning b to i. What’s interesting is that the same doesn’t work with strings even though there are constructors, for example from int to String and from String to int.
# both of these generate parsing errors
func itostr() -> String:
return 1
func strtoi() -> int:
return "Hello World"
I believe there should at least be a warning when values are automatically casted like that.
Personally, what I found most interesting/confusing regarding casting was this:
bgives an error, even though the parameters for lerp() are all of type Variant - the error is that the second argument should be int. This only seems to happen with inbuilt methods, that the types get aligned according to the first type provided, at least in this case. So here, there actually isn’t any automatic casting happening.
I was about to say that this makes more sense since lerp() interpolates between two values of the same type and in your example it’d be unclear whether the type of the value that is interpolated should be int or float. But I tested it and lerp() actually casts integers to floats.
Both lerp(0, 1, 0.5) and lerp(0.0, 1.0, 0.5) return 0.5 which is interesting.