Callable, Lambda & Functional GDScript
🪝 Callable, Anonymous Functions & Lambdas in GDScript 2.0
In Godot 4, functions are first-class citizens represented by the Callable type. You can store functions in variables, pass them as arguments to higher-order functions, and create anonymous inline Lambdas (func(args): ...).
⚡ 1. Lambda Syntax & Inline Closures
extends Node
func _ready() -> void:
# 1. Storing an anonymous function in a variable
var multiply_by_two: Callable = func(val: int) -> int:
return val * 2
print(multiply_by_two.call(10)) # Outputs: 20
# 2. Capturing outer scope variables (Closures)
var bonus_damage: float = 15.0
var calculate_damage: Callable = func(base_dmg: float) -> float:
return base_dmg + bonus_damage # Captures bonus_damage from parent scope
print("Total Damage: ", calculate_damage.call(20.0)) # Outputs: 35.0
📊 2. Functional Array Processing (map, filter, reduce)
GDScript 2.0 provides functional array helpers powered by Callable:
func process_player_inventory(items: Array[Dictionary]) -> void:
# Filter: Keep only weapons
var weapons: Array = items.filter(func(item: Dictionary) -> bool:
return item.get("type", "") == "weapon"
)
# Map: Extract just the damage numbers
var damage_values: Array = weapons.map(func(item: Dictionary) -> float:
return item.get("damage", 0.0)
)
# Reduce: Sum all damage
var total_damage: float = damage_values.reduce(func(accum: float, val: float) -> float:
return accum + val
, 0.0)
print("Total Arsenal Firepower: ", total_damage)
🔗 Related Notes
- Intro Into Gdscript — Static typing and GDScript basics.
- Signals, Callbacks & Event Bus — Binding callables to signal listeners (
signal.connect(my_callable)). - Coroutines, Await & Async Execution — Awaiting callable results.