ID:139330
 
Code:
    proc
FormatText( msg as text, LineWidth=100, letter_spacing=1 )
var/id = "([LineWidth])([letter_spacing])([msg])"
if(!cached_formats.Find(msg))
var/list/words = text2list(msg, " ")
var/formatted_text = ""
var/word
//var/x_length = 0
var/word_size= 0
var/word_length = 0
var/space_left = LineWidth
for(var/i=1 to words.len)
word = words[i]
word_length = length(word)
word_size = (word_length*width)+(word_length*letter_spacing)
if(word_size+1 > space_left && word_size < LineWidth)
formatted_text += "\n"
space_left = LineWidth
formatted_text += word+" "
space_left -= word_size+1
cached_formats.Add(id)
cached_formats[id] = formatted_text
return cached_formats[id]


Problem description:
I'm trying make make text wrap in my screen text proc but for some reason it doesn't want to work...It works the first time it has to wrap the text but then it stops working for some reason and starts line breaking in a wierd way.

There are two obvious issues I see. First, you are searching cached_formats for the string msg, but you never actually add msg to the list, you add id instead. So, that first if() should search for id instead of msg.

The second issue is that you seem to not be counting the space character. So, consider the string "a b c d e f", with width 10, LineWidth 100, and letter_spacing 0. You'd get the words "a", "b", etc. Each would have word_size of 10, so space_left would be reduced by 11 for each word (not sure why there's a +1 there, by the way), and you'd fit all six characters easily, with space_left being 34. However, you would have twelve characters on the line: "a b c d e f ", with a total width of 120 which would not fit.

So, your calculation for word_size should instead be ((word_length+1) * (width + letter_spacing)). However: that's not quite accurate, as the extra space at the end should not prevent you from adding the word as the last word on a line. So rather, you should subtract (word_size + (width + letter_spacing) from space_left.

Also: still not sure where word_size+1 comes from in either of the two places you are using it.
In response to Garthor
Thanks, and I added the '+1' to account for the spaces that would be added.