Passing signal arguments into variable's custom setter

Godot Version

4.2.1

Question

When connecting a custom signal with arguments in the emit, I am trying to use that signal to alter a variable using a custom setter. I’ve been able to get the argument through when the setter has a custom function:

var hearts = 4: set = set_hearts, get = get_hearts
func set_hearts(value):
	hearts = clamp(value, 0, max_hearts)
	if heart_ui_full != null:
		heart_ui_full.size.x = hearts * HEART_SIZE
func get_hearts():
	return hearts

[…]

func _ready():
	max_hearts = PlayerStats.max_health
	hearts = PlayerStats.health
	PlayerStats.health_changed.connect(set_hearts)

That works, but with unnamed setters it doesn’t:

var max_hearts = 4:
	set(value):
		max_hearts = max(value, 1)
		hearts = min(hearts, max_hearts)
		if heart_ui_empty != null:
			heart_ui_empty.size.x = max_hearts * HEART_SIZE
	get:
		return max_hearts

[…]

func _ready():
	max_hearts = PlayerStats.max_health
	hearts = PlayerStats.health
	PlayerStats.max_health_changed.connect(max_hearts)

This gives the error “Invalid type in function connect in base signal. Cannot convert argument 1 from int to Callable.”

I’ve tried max_hearts.set() to no avail as well “nonexistant function set in base int”

For now, I can use the first method, but would like to know what I’m doing wrong and how to fix it to use the unnamed setter.

When you use set(value) you are no longer using a function. In the connect, the argument, max_hearts, must be a function, but it’s an int.

You could try an anon lambda:

...connect(func(n): max_hearts=n) Assuming you emit an int argument.

1 Like