Default Arguments
Lesson 11 of 48 in Coddy's GDScript for C# Developers course.
C# permits optional parameters and named argument calls. GDScript supports trailing defaults but calls use positional arguments rather than arbitrary C# parameter names. Place required parameters before optional ones and preserve their order. A default does not create a set of overloaded methods. For owned mutable state, initialize a container deliberately in each instance rather than assuming a default expression gives the desired sharing behavior. The example repeats text, distinct from the delimiter framing task.
Complete C# comparison. Compile all listed C# files together; Program.Main is the entry point.
C# file Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {
static string Repeat(string text,int count=2) { return String.Concat(Enumerable.Repeat(text,count)); }
public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(Repeat("ha"));
}
}C# output:
hahaGDScript example file main.gd:
extends Node
func _ready() -> void:
print(repeat_text("ha"))
func repeat_text(text: String, count: int = 2) -> String:
return text.repeat(count)GDScript output:
hahaChallenge
EasyImplement static surround(text:String,left:String="[",right:String="]")->String in TextFrame. Solve uses defaults for one input and the supplied delimiters for three inputs.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in text_frame.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
if TextFrame.surround("q") != "[q]" or TextFrame.surround("q", "{", "}") != "{q}":
return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for C# Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler