Menu
CoddyTech

Declare a Function

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 51 of 92.

A function is a block of code with a name. You write it once, and you run it, or call it, whenever you need it.

Look at this code:

print("Welcome to Coddy")
print("New session...")
print("Welcome to Coddy")
print("Another session...")
print("Welcome to Coddy")

The welcome line is written three times. To change the message, you would have to edit all three. A function fixes that.

Declare a function with func, a name, parentheses and a colon. The statements of the function are indented below it:

func greet():
	print("Welcome to Coddy")

You already know one function: _ready(), which Godot calls when the program starts. Your own functions go at the top level of the file, next to _ready() and not inside it. To call one, write its name followed by parentheses:

extends Node

func _ready():
	greet()
	print("New session...")
	greet()
	print("Another session...")
	greet()

func greet():
	print("Welcome to Coddy")

This prints the same five lines as the first example, and the message now lives in one place.

The order of the functions in the file does not matter: _ready() can call a function written below it. Function names use snake_case, like variables.

challenge icon

Challenge

Easy

The program reads a whole number n and has a loop that runs n times.

  1. Below _ready(), declare a function named print_large_number that prints the number 50005000.
  2. Inside the loop, replace pass with a call to print_large_number().

For the input 3, the output is:

50005000
50005000
50005000

Try it yourself

extends Node

func _ready():
	var n := int(OS.read_string_from_stdin())
	for i in range(n):
		# Call print_large_number() here
		pass

# Declare the function print_large_number() below
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