signalsgodotstrong-typinggdscriptdynamic-typing

How do I emit a signal argument as an int instead of string?


In Godot 3.3, I'm trying to make a Label respond to text entered through a LineEdit node. I connected the objects and can emit the signal, but the signal is only ever sent as a string, not as the int that I want. When I use the strong typing, I get the error "Cannot convert argument 1 from String to int.."

When I stop using strong typing and go back to weak typing, I have no errors. How do I emit a signal and make sure it's the data type I specified?

In the LineEdit node: emit_signal("text_entered", text as int)

In the Label node:

func _on_text_entered(value :int): <-This function header causes errors

func _on_text_entered(value): <-While this one does not.


Solution

  • In your LineEdit, "text_entered" is a build-in signal that the LineEdit uses. And when the LineEdit uses it, it sends Strings (regardless of what you send when you use it).

    When you send an int, there is no problem with the connected function taking int. But when LineEdit sends a String (as it does) the type does not match, and you get an error.


    To answer the question on the title:

    How do I emit a signal argument as an int instead of string?

    You are doing it. The code emit_signal("text_entered", text as int) is correct.

    The problem is that LineEdit will send Strings as well.

    Of course, when you don't specify the type in the connected function, it can take both the int you send, and the String that LineEdit send.


    Solution?

    Declare a new signal. For example number_entered:

    signal number_entered(number)
    

    And emit that:

    emit_signal("number_entered", text as int)
    

    Since this is a custom signal you are declaring, LineEdit does not use it, and you would be in control on what you send. So you can connect your function that takes int to that signal, and it should give you no problems.