Menu
CoddyTech

Default Arguments

Lesson 11 of 48 in Coddy's GDScript for Lua Developers course.

Lua parameters omitted by a caller arrive as nil. A function implements defaults explicitly, often by checking == nil. Using or instead also replaces false, so it is wrong when false is a meaningful argument. GDScript supports defaults in parameter declarations and callers may omit trailing optional arguments. Keep positional order; a missing middle argument does not shift the remaining parameters. An explicit default is not an overload. For per-instance mutable state, create a fresh container during construction. These examples repeat text; the task applies a different framing operation.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local function repeat_text(text, count)
  if count == nil then count = 2 end
  return string.rep(text, count)
end
print(repeat_text("ha"))

Lua output:

haha

GDScript 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:

haha
challenge icon

Challenge

Easy

Implement static surround(text:String,left:String="[",right:String="]")->String in TextFrame. The solve function 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. The supplied main.gd 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Lua Developers

Practice on your own: Online GDScript compiler