Advertisement
krock186

core.wrap_text

Aug 1st, 2017
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.24 KB | None | 0 0
  1. --[[
  2. description.txt test contents:
  3.  
  4. Loremipsumdolorsitametconsetetursadipscingelitrseddiamnonumyeirmodtemporinviduntutlaboreetdoloremagnaaliquyamerat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
  5. I can
  6. add
  7. more
  8. lines
  9. like
  10. this
  11. ]]
  12.  
  13. function core.wrap_text(text, limit)
  14.     text = text:gsub("\r", ""):trim()
  15.     if text:len() <= limit then
  16.         return {text}
  17.     end
  18.     local retval = {}
  19.     if limit == 1 then
  20.         text = text:gsub("%s+", "")
  21.         text:gsub(".", function(c)
  22.             table.insert(retval, c)
  23.         end)
  24.         return retval
  25.     end
  26.     while text:len() > 0 do
  27.         local maxlen = math.min(text:len(), limit)
  28.         local s = text:sub(1, maxlen)
  29.         local space = s:reverse():find(" ") or 0
  30.         local line  = s:find("\n")
  31.         local splitpos = (line and line - 1)
  32.             or (maxlen - space)
  33.  
  34.         if not line and text:len() <= limit then
  35.             retval[#retval + 1] = text
  36.             break
  37.         end
  38.         if not line and splitpos == limit then
  39.             retval[#retval + 1] =
  40.                 s:sub(1, limit - 1) .. "-"
  41.             text = text:sub(limit + 1,
  42.                 text:len())
  43.         else
  44.             retval[#retval + 1] = s:sub(1, splitpos)
  45.             text = text:sub(splitpos + 2,
  46.                 text:len())
  47.         end
  48.     end
  49.     return retval
  50. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement