Menu
CoddyTech

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 icon

Challenge

Easy

The program reads a player name into player.

  1. Below _ready(), declare a function greet with two parameters: player_name, and greeting with the default value "Hello". It prints the greeting, a comma and a space, the name, and !.
  2. In _ready(), call greet(player), then greet(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
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