Return
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 53 of 92.
The return statement sends a value back from a function to the code that called it. The call then stands for that value:
func get_max_hp():
return 100var hp: int = get_max_hp()
print(hp)hp holds 100, the value the function returned, so the program prints 100.
A function with parameters can return a result calculated from them. You can store the result, print it, or use it in an expression:
func square(n):
return n * nprint(square(4))
print(square(3) + 1)16
10return also ends the function. The lines after it in the same block do not run:
func check_age(age):
if age >= 18:
return "adult"
return "minor"check_age(20) returns "adult" and stops. check_age(12) skips the if block and returns "minor".
A function without return gives back null.
These functions do not say what type they return, so GDScript cannot infer a type from them: var hp := get_max_hp() is an error. Write the type of the variable yourself, as in var hp: int = get_max_hp(). The next lesson shows how a function declares its return type.
Challenge
Easy- Below
_ready(), declare a functionsquare_numberwith one parametern. It returnsn * n. - In
_ready(), callsquare_number()withinput_numand store the returned value in a variable namedresult. - Print
result.
For the input 5, the output is:
25Try it yourself
extends Node
func _ready():
var input_num := int(OS.read_string_from_stdin())
# Store square_number(input_num) in result, then print result
# Declare square_number(n) below: it returns n * n
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler