Default Values
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 57 of 92.
A parameter can have a default value, written with = in the declaration. A call can then leave that argument out, and the parameter gets the default:
func greet(player, greeting = "Hello"):
print(greeting, ", ", player, "!")greet("Ana")
greet("Ana", "Welcome back")Hello, Ana!
Welcome back, Ana!The first call passes one argument, so greeting is "Hello". The second call passes its own value, which replaces the default.
A function can have several default values, and typed parameters can have them too:
func spawn(enemy: String, count: int = 1, speed: float = 2.5) -> void:
print(count, " x ", enemy, " at speed ", speed)spawn("bat") prints 1 x bat at speed 2.5, and spawn("bat", 3) prints 3 x bat at speed 2.5. Arguments still fill the parameters in order, so you cannot pass speed without also passing count.
Parameters with a default value must come after the ones without. func greet(greeting = "Hello", player): is an error: "Cannot have mandatory parameters after optional parameters".
Challenge
EasyThe program reads a player name into player.
- Below
_ready(), declare a functiongreetwith two parameters:player_name, andgreetingwith the default value"Hello". It prints the greeting, a comma and a space, the name, and!. - In
_ready(), callgreet(player), thengreet(player, "Welcome back").
For the input Ana, the output is:
Hello, Ana!
Welcome back, Ana!Try it yourself
extends Node
func _ready():
var player := OS.read_string_from_stdin()
# Call greet(player), then greet(player, "Welcome back")
# Declare greet() below, with "Hello" as the default greeting
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