How to make a class "printable"?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By monnef

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).

:bust_in_silhouette: Reply From: Eric Ellingson

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)
:bust_in_silhouette: Reply From: Dlean Jeans

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)
:bust_in_silhouette: Reply From: admin

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