Lambda Functions Part 1
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 54 of 78.
A lambda is a function without a name, written as a value. You can store it in a variable like a number or a string:
var add = func(a, b): return a + bIt starts with func, the parameters and a colon, like any function, but it has no name. A body of one statement can stay on the same line.
To run a lambda stored in a variable, call its call() method with the arguments:
print(add.call(5, 3))8add(5, 3) does not work: GDScript looks for a function named add in the script and reports Function "add()" not found before the program runs.
A longer lambda has an indented block. Like any function, it needs return to give a value back:
var greet = func(player_name):
var message = "Hello, " + player_name
return message + "!"
print(greet.call("Ana"))Hello, Ana!A lambda without return gives back null, so func(n): n * 2 calculates the value and throws it away.
Parameters and the result can have types: func(n: int) -> int: return n * 2. The value of a lambda is a Callable, the GDScript type for "something you can call".
Challenge
EasyThe program reads three whole numbers, a, b and c.
- Create a lambda with three parameters,
x,yandz, that returns their product, and store it in a variable namedmultiply. - Call it with
a,bandcand print the result.
For the inputs 2, 3 and 4, the output is:
24Try it yourself
extends Node
func _ready():
var a := int(OS.read_string_from_stdin())
var b := int(OS.read_string_from_stdin())
var c := int(OS.read_string_from_stdin())
# Create the lambda multiply here
# Call multiply with a, b and c, 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