ID:195073
 
//Title: Sentence Interruption
//Credit to: Jtgibson
//Contributed by: Jtgibson
//Based from: Word Count (Jtgibson)


/*
This allows you to specify a maximum number of words that can appear in the
given string. If more words appear than the limit in the specified string, the
proc then returns the string up to that point, with an optional continuation
string inserted at the very end.


I use this proc in *Newtopia* to allow a character to run out of breath while
shouting. It costs 2 Stamina points to shout, so shouting a message that's 10
words long costs 20 Stamina points. If the person only has 8 Stamina
available, they can only shout 4 words, and all subsequent words are cut off.

> shout "You will rue this day, you foul vagabond!"
Incognito the Shrew shouts breathlessly, "You will rue this--"
*/



proc/interruptstring(string, maxcount=0, continuation="")
var/characters = length(string)

var/wordcount = 0

//Iterate through the string, toggling state if going from an alphanumeric
// to a non-alphanumeric. "'" is ignored and is considered to be the same
// type as the previous character (e.g., "that's" is one word).
var/alpha = 0
var/last_alpha_pos = 1
for(var/i = 1, i <= characters, i++)
switch(text2ascii(string,i))
if(39) continue //apostrophe
if(48 to 57, 65 to 90, 97 to 122) /*0-9, A-Z, a-z*/
//Encountered a new word, increase word count
if(!alpha)
alpha = !alpha
if(wordcount++ >= maxcount)
return "[copytext(string,1,last_alpha_pos)][continuation ? continuation : ""]"
else
if(alpha)
alpha = !alpha
last_alpha_pos = i

return string


///*
//Testing code/sample implementation:

mob/verb/test_interruptstring(string as message, maxcount as num)
usr << interruptstring(string, maxcount, "--")

//*/
I reversed the logic a little bit and introduced a variable which tracks where the last word ends, so now the trailing punctuation is included in the sentence if the maxcount is exactly equal to the number of words in the sentence.

For instance,
interruptstring("You will rue this day, you foul vagabond!",7,"--")
will yield You will rue this day, you foul-- while
interruptstring("You will rue this day, you foul vagabond!",8,"--")
will yield the full You will rue this day, you foul vagabond!.

In the previous version, the latter would yield You will rue this day, you foul vagabond--.