Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. -- Splits a string into a table
  2. function split(str, pattern)
  3. local words = {}
  4. for word in str:gmatch(pattern) do
  5. words[#words+1] = word
  6. end
  7. return words
  8. end
  9.  
  10. function textWrap(text, width)
  11. local lines = split(text, "[^\r\n]+")
  12. local widthLeft
  13. local result = {}
  14. local line = {}
  15.  
  16. -- Insert each source line into the result, one-by-one
  17. for k=1, #lines do
  18. sourceLine = lines[k]
  19. widthLeft = width -- all the width is left
  20. local words = split(sourceLine, "%S+")
  21. for l=1, #words do
  22. word = words[l]
  23. -- If the word is longer than an entire line:
  24. if #word > width then
  25. -- In case the word is longer than multible lines:
  26. while (#word > width) do
  27. -- Fit as much as possible
  28. table.insert(line, word:sub(0, widthLeft))
  29. table.insert(result, table.concat(line, " "))
  30.  
  31. -- Take the rest of the word for next round
  32. word = word:sub(widthLeft + 1)
  33. widthLeft = width
  34. line = {}
  35. end
  36.  
  37. -- The rest of the word that could share a line
  38. line = {word}
  39. widthLeft = width - (#word + 1)
  40.  
  41. -- If we have no space left in the current line
  42. elseif (#word + 1) > widthLeft then
  43. table.insert(result, table.concat(line, " "))
  44.  
  45. -- start next line
  46. line = {word}
  47. widthLeft = width - (#word + 1)
  48.  
  49. -- if we could fit the word on the line
  50. else
  51. table.insert(line, word)
  52. widthLeft = widthLeft - (#word + 1)
  53. end
  54. end
  55.  
  56. -- Insert the rest of the source line
  57. table.insert(result, table.concat(line, " "))
  58. line = {}
  59. end
  60. return result
  61. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement