Randomized Format Strings

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

As the title suggests I’m having issues with randomized format strings.

So I’ve got a variable set up like so

var desc_color = "There is a {blue} colored hat, a {blue} colored desk, and a {blue} colored critter in the room with you. "

And a function to randomize the format string.

func random_color():
	randomize()
	var colors = ["blue","azure","sapphire"]
	var blue = colors[randi() % colors.size()]
	return blue

And for what it’s worth it does manage to print out a random string every time. However it replaces each instance of {blue} with the same item like so.

“There is a sapphire colored hat, a sapphire colored desk, and a sapphire colored critter in the room with you.”

What I’m looking to do is have it randomly select an item from the array for each instance of {blue} so I get a random result for each one.

Are there any ideas how I would go about this?

:bust_in_silhouette: Reply From: Gluon

You could create three separate strings, call the random colour on each and then append them to each other e.g.

var desc_color1 = "There is a {blue} colored hat,  "

var desc_color2 = "a {blue} colored desk,  "

var desc_color3 = "and a {blue} colored critter in the room with you. "

var desc_color = desc_color1 + desc_color2 + desc_color3

you can then call random colour three different times getting a different result each time.

Would there be a way to do it without splitting everything up into multiple parts? Like through the use of a function or something?

Volk | 2023-02-07 19:58

Well the problem you are having is you need to run the function to return {blue} each time you want a unique example so no matter how you chose to do it this has to be done. For example you could have

var label1 = random_color()
var label2 = random_color()
var label3 = random_color()

var desc_color = "There is a %s colored hat, a %s colored desk, and a %s colored critter in the room with you. " % [label1, label2, label3]

print(desc_color)

This will work but either way you have to call the function 3 different times to get three results.

Gluon | 2023-02-07 20:15

Ah, okay. Thanks for the help Gluon.

Volk | 2023-02-07 23:40