Menu
CoddyTech

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 + b

It 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))
8

add(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 icon

Challenge

Easy

The program reads three whole numbers, a, b and c.

  1. Create a lambda with three parameters, x, y and z, that returns their product, and store it in a variable named multiply.
  2. Call it with a, b and c and print the result.

For the inputs 2, 3 and 4, the output is:

24

Try 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
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