Menu
CoddyTech

The _to_string Method

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 32 of 65.

Printing an object whose class does not define _to_string() shows only its class and an internal ID, which changes from run to run: <RefCounted#-9223372009541466673>. Define _to_string() and return the text that should appear instead:

# card.gd
class_name Card
extends RefCounted

var rank: String
var suit: String

func _init(new_rank: String, new_suit: String) -> void:
	rank = new_rank
	suit = new_suit

func _to_string() -> String:
	return rank + " of " + suit

Godot calls it every time the object is turned into text: by print(), by str(), by %s in a format string, and for each object inside a printed Array or Dictionary:

var card := Card.new("Queen", "hearts")
print(card) # Queen of hearts
print(str(card)) # Queen of hearts
print("You drew %s" % card) # You drew Queen of hearts
print([card, Card.new("7", "clubs")]) # [Queen of hearts, 7 of clubs]

"You drew " + card is still an error, because + joins two Strings and card is an object. Convert it first: "You drew " + str(card).

A subclass can override _to_string() and use the parent's text with super():

# wild_card.gd
class_name WildCard
extends Card

func _to_string() -> String:
	return "Wild " + super()

print(WildCard.new("King", "spades")) prints Wild King of spades.

_to_string() returns the text and prints nothing itself. The code that uses the object decides whether the text is printed, joined into a longer line or stored.

challenge icon

Challenge

Easy

Give two classes a _to_string() method:

  • PlayingCard in playing_card.gd has a rank from 2 to 14 and a suit. Its text is the rank, of and the suit, such as 7 of clubs. Ranks 11, 12, 13 and 14 are written J, Q, K and A: Q of hearts.
  • Hand in hand.gd keeps its cards in _cards. Its text is Hand (N): followed by the cards' texts joined with , , or Hand (0): empty when it has no cards.

The supplied code prints the empty hand, reads the number of cards, then one RANK SUIT line per card. It adds each card to the hand, prints Drew and the card, and finally prints the hand. For the cards 7 clubs and 12 hearts it prints:

Hand (0): empty
Drew 7 of clubs
Drew Q of hearts
Hand (2): 7 of clubs, Q of hearts

Your code goes in playing_card.gd and hand.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var hand := Hand.new()
	print(hand)
	var count := int(OS.read_string_from_stdin())
	for i in count:
		var parts := OS.read_string_from_stdin().split(" ")
		var card := PlayingCard.new(int(parts[0]), parts[1])
		hand.add(card)
		print("Drew %s" % card)
	print(hand)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler