Menu
CoddyTech

Arguments

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

A function can receive values when it is called. In the declaration, write names for them inside the parentheses. These names are the function's parameters, and they work like variables inside the function:

func greet(player):
	print("Hello, ", player, "!")

The values you pass in the call are the arguments. Each call can pass different ones:

greet("Ana")
greet("Leo")
Hello, Ana!
Hello, Leo!

Separate several parameters with commas. The arguments are matched to the parameters in order, so here player is "Mia" and score is 120:

func show_score(player, score):
	print(player, " has ", score, " points")

The call show_score("Mia", 120) prints Mia has 120 points.

A call must pass one argument for every parameter. show_score("Mia") has too few, and GDScript reports the error before the program runs.

Functions with parameters work well in loops. This function is called once for each number from 3 to 5:

func check_even(number):
	if number % 2 == 0:
		print(number, " is even")
	else:
		print(number, " is odd")
for i in range(3, 6):
	check_even(i)
3 is odd
4 is even
5 is odd
challenge icon

Challenge

Easy

The program reads two whole numbers, a and b.

  1. Below _ready(), declare a function print_product with two parameters. It prints the first parameter multiplied by the second.
  2. In _ready(), call print_product() with a and b.

For the inputs 3 and 5, the output is:

15

Try it yourself

extends Node

func _ready():
	var a := int(OS.read_string_from_stdin())
	var b := int(OS.read_string_from_stdin())
	# Call print_product() with a and b

# Declare print_product() below: it prints its two arguments multiplied
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