godotengine / godot-proposals

Godot Improvement Proposals (GIPs)
MIT License
1.1k stars 69 forks source link

Add support `Object` as argument for `String.format()` #5434

Open 4d49 opened 1 year ago

4d49 commented 1 year ago

Describe the project you are working on

Game.

Describe the problem or limitation you are having in your project

For debugging in my project, needs display useful information.

Describe the feature / enhancement and how it helps to overcome the problem or limitation

To format an Object into text, needs create temporary Dictionaries.

Describe how your proposal will work, with code, pseudo-code, mock-ups, and/or diagrams

Implementation: https://github.com/4d49/godot/commit/6f809c77cdef8552928b32d5181ea9f734c58099

If this enhancement will not be used often, can it be worked around with a few lines of script?

static func format_object(string: String, object: Object, placeholder:= "{_}") -> String:
    for p in object.get_property_list():
        string = string.replace(placeholder.replace("_", p.name), str(object.get(p.name)))

    return string

Is there a reason why this should be core and not an add-on in the asset library?

It looks useful and like part of the engine.

Calinou commented 1 year ago

Can't you override _to_string() in the object instead as follows?

extends Reference
class_name MyClass

var name = "example"
var amount = 123

func _to_string() -> String:
    return "%s %d" % [name, amount]
4d49 commented 1 year ago

Can't you override _to_string() in the object instead?

In different contexts, different templates can be used to format strings.