Last active
April 29, 2022 13:41
-
-
Save caligari87/595c8fb513e1d476b1467b90a9175715 to your computer and use it in GitHub Desktop.
A simple string variation builder (GZDoom / ZScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Make a string from a variable template | |
static string BuildVariableString(string msg){ | |
// some input example strings: | |
// "an empty {beer|soda|wine|champagne} bottle. {It is {cracked|broken|unlabeled}.}" | |
// "a {small|large|||} plush {emoji|cacodemon|teddy bear|furbie} toy." | |
// Collapse substrings, repeat until no more { } | |
while(true){ | |
int LeftBrace = msg.RightIndexOf("{"); // find the rightmost left-brace { | |
int RightBrace = msg.IndexOf("}",LeftBrace+1); // find the nearest matching right-brace } | |
if (LeftBrace == -1 || RightBrace == -1) { break; } // stop looping if no more {} | |
string substring = msg.Mid(LeftBrace+1, (RightBrace-LeftBrace)-1); // get inner text string, without {} braces | |
msg.Remove(LeftBrace+1, (RightBrace-LeftBrace)-1); // remove the inner text string, leave the {} braces | |
// build an array of substrings from the extracted string, separated by | | |
array<string> substrings; | |
substring.Split(substrings,"|"); | |
// pick a random sub-string from the {|||} set | |
// replace the leftover {} with the picked substring | |
// empty || pairs can be used for random null results | |
msg.Replace("{}", substrings[random(0,substrings.Size()-1)]); | |
} | |
// Remove double-spaces, repeat until no more | |
while (true) { | |
if (msg.IndexOf(" ", 0) > -1) { msg.Replace(" ", " "); } | |
else { break; } | |
} | |
return msg; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment