Skip to content

Instantly share code, notes, and snippets.

@cgbeutler
Created February 4, 2021 23:20
Show Gist options
  • Save cgbeutler/7d59adf99d37f4bfac12e0e39b2727f5 to your computer and use it in GitHub Desktop.
Save cgbeutler/7d59adf99d37f4bfac12e0e39b2727f5 to your computer and use it in GitHub Desktop.
Helper class for Godot's connect and disconnect. Also a proof of concept for a Result class.
tool class_name help_obj
# Like the default connect, but doesn't push error if already connected
static func try_connect( source: Object, sig: String, target: Object, method: String, binds := [], flags := 0 ) -> SignalResult:
if not source.has_signal(sig):
return SignalResult.new( ERR_INVALID_PARAMETER, str("Can't connect: Signal '", sig, "' missing from object.") )
if not(flags & Object.CONNECT_REFERENCE_COUNTED) and source.is_connected(sig, target, method):
return SignalResult.new( ERR_INVALID_PARAMETER, str("Can't connect: Target already connected to signal '", sig, "'.") )
return SignalResult.new( source.connect(sig, target, method, binds, flags), "" )
# Like the default disconnect, but doesn't push error if not connected
static func try_disconnect( source: Object, sig: String, target: Object, method: String ) -> SignalResult:
if not source.has_signal(sig):
return SignalResult.new( ERR_INVALID_PARAMETER, str("Can't disconnect: Signal '", sig, "' missing from object.") )
if not source.is_connected(sig, target, method):
return SignalResult.new( ERR_INVALID_PARAMETER, str("Can't disconnect: Target was not connected to signal '", sig, "'") )
source.disconnect(sig, target, method)
return SignalResult.new( OK, "" )
# Pushes an error if the error code is not checked before it the obj gets deleted
class SignalResult extends Reference:
var __error_checked := false
var __error := OK
var error :int setget ,get_error
func get_error() -> int:
__error_checked = true
return __error
func has_error() -> bool:
return get_error() != OK
var error_message :String
func _init( p_error: int, p_error_message: String ):
__error = p_error
error_message = p_error_message
return self
func _to_string() -> String:
if __error == OK and not len(error_message):
return "OK"
return str(error_message, " (Err: ", __error, ")")
func _notification(what):
if what == NOTIFICATION_PREDELETE:
if __error_checked or __error == OK:
return
push_error(str(error_message, " (Err: ", __error, ")"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment