Help with variables in Strings

Godot Version

Godot 4.1.1

Question

The plan is for the player to put a name in a variable stored in a global script. The way the player inserts the name is not done but I don’t think it’s important for this. The variable is “your_name”

And what I was thinking was to put that variable on a string in the editor

Something like this. Not in the code, I know that is posible.

Is this even posible? If it is, how would you implement it?

Thank you.

Decide on some prefix or delimiters that signifies a “variable” in your texts. It can be $your_name or [your_name], then use regular expressions to replace that with the actual name in the string.

Where would I put the prefix/delimiter? On the code?

On the words in your text that you want to represent variables. So similarly to what you actually already have: Hello, my name is $your_name

$your_name now represents a “variable” that needs to be replaced with the actual name. Since there is a specific prefix, it’s easy to do search/replace operation using regex.

I do have it.

And also I have the global variable reference in the actual code of the text.

But when I run the game, it says $your_name instead of what the variable is.

Do I need to do something more? I’m sorry if it is to many questions

As mentioned in the original reply, you need to use regex to replace your variables in text.

I think parametrised string would work in your case perfectly.

Ref:

Yeah String.format() is simpler than regex but sufficient for what you’re trying to do.

I’m not really understanding any of both methods. I mean I do kinda understand the second one with format strings, but I’m not able to implement it in my case.

Do you assign the formatted string after it gets formatted?

I’ve quick clobbered it together so do verify but this should basically work

extends Label

var your_name: String = "MySuperCoolName" #In YourCase Global.your_name

func _ready() -> void:
	text = "Your name %s" % your_name # Technically could go instead of your_name just Global.your_name if you don't need the local variable.
	self.text = "Your name %s" % your_name # Same as above but more explicit that it's a 'self-assigned' in case of the Label example.

I’ve not tested it (too much over-head to setup and 100% validate) but hopefully gives you rough idea.

It does work!!!

Thank you very much

And thank you too for your help.

Tinker around with it to get the feel for it.

hanamaru-kindergarten-anime

yeah, it works exacly as I espected