Menu
CoddyTech

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 100
var 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 * n
print(square(4))
print(square(3) + 1)
16
10

return 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 icon

Challenge

Easy
  1. Below _ready(), declare a function square_number with one parameter n. It returns n * n.
  2. In _ready(), call square_number() with input_num and store the returned value in a variable named result.
  3. Print result.

For the input 5, the output is:

25

Try 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler