Menu
CoddyTech

Lambda Functions Part 2

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 55 of 78.

A one-line lambda can choose its result with the ternary operator, value_if_true if condition else value_if_false:

var check_age = func(age): return "Adult" if age >= 18 else "Minor"
print(check_age.call(20)) # Adult

For more than two cases, chain a second ternary after else, or write the lambda as a block with if and elif:

var grade = func(score):
	if score == 100:
		return "Perfect"
	elif score >= 60:
		return "Pass"
	return "Fail"
print(grade.call(75)) # Pass

Because a lambda is a value, you can pass it to a function. Declare the parameter with the type Callable and run it with call():

func apply_twice(fn: Callable, value):
	return fn.call(fn.call(value))
print(apply_twice(func(n): return n + 3, 1)) # 7

A named function can be passed the same way: write its name without parentheses, as in apply_twice(double, 5).

Built-in methods take functions too. sort_custom() sorts an array with a lambda that receives two elements and returns true when the first one must come first:

var scores = [40, 90, 75]
scores.sort_custom(func(a, b): return a > b)
print(scores) # [90, 75, 40]

A lambda can read the local variables around it, but it copies their values when it is created. Changing such a variable afterwards does not reach the lambda, and assigning to it inside the lambda does not change the variable outside.

challenge icon

Challenge

Easy

The program reads a whole number. Create a lambda and store it in a variable named categorize_number. It takes one number and returns:

  • Positive if the number is greater than 0
  • Zero if the number is 0
  • Negative if the number is less than 0

Call it with the number you read and print the result. For the input 10, the output is:

Positive

Try it yourself

extends Node

func _ready():
	var number := int(OS.read_string_from_stdin())
	# Create the lambda categorize_number here

	# Call it with number and print the result
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler