Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function wrap_text(text, width) -- break the text into lines and return an array of lines that are approximately the allowed width
- local lines = {} -- dialogue lines of the currect width
- local cur_line = "" -- a container for the line being currently built
- local cur_letter=1 -- points to one letter in the text
- for cur_letter=1,#text do -- point to each letter in the text
- 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)?
- local r = flr(width/4) - #cur_line --how much room, in characters, is left in the width of the diaglogue box?
- if c <= r then --if there's room for the whole next word,
- cur_line = cur_line .. text[cur_letter] --add the next letter to the line being built
- end
- if c > r then --if the whole next word is longer than the space left in the dialogue box
- add(lines, cur_line) --this line being built is complete, add it to the array of lines
- cur_line = "" --clear the container
- cur_line = cur_line .. text[cur_letter] --the character currently pointed to becomes the beginning of the new line
- end
- end
- if #cur_line > 0 then --after pointing to each letter, if there's a partial line in the container
- add(lines, cur_line) --add it to the array of lines
- end
- return lines --return the array of lines
- end
- function chars_to_space_or_end(text, index) --count the number of letters to the next space (or last letter)
- ptr=index --point to each letter, starting with wherever we are on the dialogue line
- counter=0 --number of letters to the next space or last letter
- while text[ptr] ~= " " and ptr ~= #text do --if this letter isn't a space or the last letter
- counter += 1 --count it
- ptr += 1 --move to the next letter
- end
- if ptr == #text then --if you landed on the last letter
- counter += 1 --count it (because it caused the while block to be skipped, and didn't get counted)
- end
- return counter --return the number of letters
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement