Created
February 24, 2025 05:54
-
-
Save CodeZombie/ab87f5c004364a522c5a9efc53038bd2 to your computer and use it in GitHub Desktop.
Self deleting lambda signals in Godot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extends Node | |
signal sig | |
class SigTest: | |
var x: int = 0 | |
func on_signal(sig: Signal, callable: Callable): | |
var this_object_weakref: WeakRef = weakref(self) | |
var wrapped_callable: Callable = func(f: Callable): | |
if this_object_weakref.get_ref() == null: | |
sig.disconnect(f) | |
return | |
callable.call(this_object_weakref.get_ref()) | |
sig.connect(wrapped_callable.bind(wrapped_callable)) | |
func _ready(): | |
var my_sigtest: SigTest = SigTest.new() | |
my_sigtest.on_signal(self.sig, func(st: SigTest): | |
print("hello")) | |
my_sigtest.on_signal(self.sig, func(st: SigTest): | |
print("world")) | |
sig.emit() | |
print(sig.get_connections()) | |
func _process(delta: float): | |
print(sig.get_connections()) | |
sig.emit() | |
print('emitting') | |
print(sig.get_connections()) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here I present to you, oh fortunate reader, a
self-disconnecting object-bound anonymous signal connection
pattern for gdscript, for your reading pleasure.