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 oddChallenge
EasyThe program reads two whole numbers, a and b.
- Below
_ready(), declare a functionprint_productwith two parameters. It prints the first parameter multiplied by the second. - In
_ready(), callprint_product()withaandb.
For the inputs 3 and 5, the output is:
15Try 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
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