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)) # AdultFor 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)) # PassBecause 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)) # 7A 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
EasyThe program reads a whole number. Create a lambda and store it in a variable named categorize_number. It takes one number and returns:
Positiveif the number is greater than0Zeroif the number is0Negativeif the number is less than0
Call it with the number you read and print the result. For the input 10, the output is:
PositiveTry 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter10Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested Array2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler