How to add a method to the String type?

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

Hi, for the use of a project I would like to create an extension of the type String (named Message) but I don’t know how to do this. I know how to extends a Node but not a type and it doesn’t seem to be as simply as “extends String” :wink:

for example I would be able to do the following :

var msg : Message
msg = “GZKKI >IEKS”

var msg2 : Message
msg2 = msg.decode()

//msg2 = “HELLO WORLD”

where msg.decode is a method of the type message.

How to do this?

thanks in advance for your help !

Simon

:bust_in_silhouette: Reply From: Dlean Jeans

I think it’s not possible. Although if you insist, you can extend Resource:

class_name Message
extends Resource

var value:String

func _init(value):
    self.value = value

func decode():
    var decoded = value
    # decoding
    return decoded

Usage:

var msg:Message = Message('GZKKI >IEKS')
var msg2 = msg.decode()
print(msg2) # HELLO WORLD ???
msg.value = 'assign to other value'

Alternatively, you can write a static decode function:

class_name Decoder

static func decode(value:String):
    # decoding
    return decoded_value

Usage:

print(Decoder.decode('GZKKI >IEKS')) # HELLO WORLD ???

Thanks for your response. I would have prefer to avoid static decode funciton but I think I won’t have the choice…

Thanks ! :slight_smile:

simLC | 2019-06-14 12:35