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
EasyThe program reads a whole number n and has a loop that runs n times.
- Below
_ready(), declare a function namedprint_large_numberthat prints the number50005000. - Inside the loop, replace
passwith a call toprint_large_number().
For the input 3, the output is:
50005000
50005000
50005000Try 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
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