Advertisement
janac

Untitled

Jun 13th, 2025 (edited)
478
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.96 KB | None | 0 0
  1. function wrap_text(text, width) -- break the text into lines and return an array of lines that are approximately the allowed width
  2.  local lines = {} -- dialogue lines of the currect width
  3.  local cur_line = "" -- a container for the line being currently built
  4.  local cur_letter=1 -- points to one letter in the text
  5.  for cur_letter=1,#text do -- point to each letter in the text
  6.         local c = chars_to_space_or_end(text, cur_letter)--how many letters to the next space or the end of the dialogue (including the current one)?
  7.         local r = flr(width/4) - #cur_line --how much room, in characters, is left in the width of the diaglogue box?
  8.         if c <= r then --if there's room for the whole next word,
  9.             cur_line = cur_line .. text[cur_letter] --add the next letter to the line being built
  10.         end
  11.         if c > r then --if the whole next word is longer than the space left in the dialogue box
  12.          add(lines, cur_line) --this line being built is complete, add it to the array of lines
  13.          cur_line = "" --clear the container
  14.          cur_line = cur_line .. text[cur_letter] --the character currently pointed to becomes the beginning of the new line
  15.         end
  16.  end
  17.  if #cur_line > 0 then --after pointing to each letter, if there's a partial line in the container
  18.   add(lines, cur_line) --add it to the array of lines
  19.  end
  20.  return lines --return the array of lines
  21. end
  22.  
  23. function chars_to_space_or_end(text, index) --count the number of letters to the next space (or last letter)
  24.     ptr=index --point to each letter, starting with wherever we are on the dialogue line
  25.     counter=0 --number of letters to the next space or last letter
  26.     while text[ptr] ~= " " and ptr ~= #text do --if this letter isn't a space or the last letter
  27.         counter += 1 --count it
  28.         ptr += 1 --move to the next letter
  29.     end
  30.     if ptr == #text then --if you landed on the last letter
  31.      counter += 1 --count it (because it caused the while block to be skipped, and didn't get counted)
  32.     end
  33.     return counter --return the number of letters
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement