Advertisement
Badwrong

GameMaker - String Insert Newlines

Mar 23rd, 2021 (edited)
607
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function StringInsertNewlines(_string, _lineWidth) {
  2.  
  3.     // "String" macros
  4.     #macro S_LINE "\n"
  5.     #macro S_SPACE " "
  6.     #macro S_EMPTY ""
  7.  
  8.     _string += S_SPACE; // Add a space at end to ensure last word isn't missed
  9.  
  10.     var _stringOut = S_EMPTY, _word = S_EMPTY, _chr,
  11.         _totalWidth = 0,
  12.         _wordWidth  = 0;
  13.  
  14.     for (var _c = 1, _count = string_length(_string) + 1, _chr; _c < _count; _c++)
  15.     {
  16.         // Get next character and add to current word
  17.         _chr = string_char_at(_string, _c);
  18.         _word += _chr;
  19.        
  20.         if (_chr == S_SPACE)  // If a space add the word and compare width
  21.         {
  22.             _wordWidth = string_width(_word);
  23.            
  24.             if (_totalWidth > 0)
  25.             {
  26.                 _totalWidth += _wordWidth;
  27.                                                            
  28.                 if (_totalWidth >= _lineWidth)  
  29.                 {   // Line would be too long, so add a newline before word
  30.                     _stringOut += S_LINE + _word;
  31.                     _totalWidth = _wordWidth;
  32.                 }
  33.                 else _stringOut += _word; // Add current word to entire string
  34.             }
  35.             else
  36.             {   // First word on line should never have a newline
  37.                 _totalWidth += _wordWidth;
  38.                 _stringOut  += _word;
  39.             }
  40.            
  41.             // Reset the current word
  42.             _word = S_EMPTY;
  43.         }
  44.     }
  45.  
  46.     return _stringOut;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement