+1 vote

I am looking for something similar to toString method in Scala or show typeclass from Haskell. Example:

extends Node

class C:
    var x
    func _init(nx = 0):
        x = nx

func _ready():
    print(C.new(4))

Output:

[Reference:978]

Example of desired output (defined in class):

C(4)

Is there some standard way of doing this in GDScript*, or adhoc method is only solution?


*: For example a method which gets called by print (I failed to find documentation for print, the search in docs is a bit weird).

in Engine by (135 points)

3 Answers

+2 votes
Best answer

Add the function _to_string() to your class

class C:
    var x
    func _init(nx = 0):
        x = nx

    func _to_string():
        return "C(%s)" % x

func _ready():
    print(C.new(4))

Output :

C(4)

I found the answer in this discussion : https://github.com/godotengine/godot/pull/27886

by (58 points)
selected by
–2 votes

Unless this has since changed, it doesn't seem like this is possible yet:

As an alternative, you could write your own utility singleton that handles it

extends Node
class_name Utils

static func print(obj):
    match typeof(obj):
         typeof(SomeClass):
               print(obj.property, obj.property, ...)

Then you can call it like:

Utils.print(some_object)
by (1,660 points)
+2 votes

An obvious alternative is simply add a to_string() function, no need for a singleton:

class C:
    var x
    func _init(nx = 0):
        x = nx

    func to_string():
        return 'C(%s)' % x

func _ready():
    print(C.new(4).to_string())

Output:

C(4)
by (4,225 points)
edited by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.