return is a keyword that ends a function and sends a value back to the caller.
In GDScript, you can return any value from a function, but this return value should match the return type declared in the function's signature.
For example, this function returns an integer:
funcreturn_five()->int:return5
But if I wrote this, Godot would give me an error:
funcreturn_five()->int:return"five"
Because "five" is a string, not an integer.
Branches
This function is an error too. Can you spot it?
var should_return_five := true
funcreturn_five()->int:if should_return_five == true:return5else:return null
The declared return type is an int, but the effective return type is a mix of either int or null. The two don't match. To make the function valid, I could return 0 in the else branch.
This example is obvious, but there are cases where Godot might not be able to tell if a function's return matches the signature, even if you're able to. Consider the below:
var default_return =0funcreturn_five()->int:if some_condition:return5return default_return
In this case, Godot can't tell if the function will always return an integer because default_return is not typed. While you know it's an intint, there's no guarantee it won't change. If you're sure it won't, you can add a type hint:
The as keyword casts the variable. It's a way to tell Godot "I know what I'm doing, trust me".
NOTE:
This is just a simplified example; in this case, typing default_return would be a clearly better solution than using as.
Returning nothing
While both mathematical functions and programming functions share the same name, they are not the same thing.
A function can indeed work like a math function:
funcmultiply_by_ten(number:int)->int:return number *10
That's what we call a pure function, because it is self-contained. It doesn't use anything beside its arguments.
But it can also affect an external variable, without returning anything:
var counter :=0funcincrement_counter(number:int)->void:
counter += number
Affecting the world around is what we call a side effect. Notice the lack of return in this function; it does something, but doesn't return anything.
Of course, there's nothing stopping us from writing a function that does both. This function multiplies by 10, returns the result, but also counts how many times it was called:
var counter :=0funcmultiply_by_ten(number:int)->int:
counter +=1return number *10
This is a function with both side effects (affects the world around it) and a return value. These functions are very common.
Become an Indie Gamedev with GDQuest!in GDSchool
Don't stop here. Step-by-step tutorials are fun but they only take you so far.
Try one of our proven study programs to become an independent Gamedev truly capable of realizing the games you’ve always wanted to make.