jille_Jr

CC: Cannon mail [Server] - util.lua

Feb 22nd, 2016
113
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- util.lua
  2.  
  3. function tcontains(t,element)
  4.   for _,value in pairs(t) do
  5.     if element == value then
  6.       return true
  7.     end
  8.   end
  9.   return false
  10. end
  11.  
  12. function wordwrap(str, callback, maxLength, maxRows)
  13.     if type(callback) == "table" then
  14.         local t = callback
  15.         callback = function(row) table.insert(t, row) end
  16.     end
  17.  
  18.     local rows = 0
  19.     while #str > 1 do
  20.         if type(maxRows) == "number"
  21.         and rows >= maxRows and (#str + 3 > maxLength) then
  22.             callback(str:sub(1,maxLength-3) .. "...")
  23.             return str
  24.         else
  25.             local pre = ""
  26.             pre, str = smartSplit(str, maxLength)
  27.             callback(pre)
  28.             rows = rows + 1
  29.         end
  30.     end
  31.  
  32.     return nil
  33. end
  34.  
  35. -- split a string at a space if possible
  36. function smartSplit(str, maxLength)
  37.     if #str < maxLength then
  38.         return str, ""
  39.     end
  40.  
  41.     local pre = str:sub(1,maxLength)
  42.     local post = str:sub(maxLength+1,-1)
  43.  
  44.     -- check from first to last
  45.     for index = 1,math.min(#str,maxLength) do
  46.         local char = str:sub(index,index)
  47.  
  48.         if char == "\n" then
  49.             pre = str:sub(1,index-1)
  50.             post = str:sub(index+1,-1)
  51.             return pre, post
  52.         end
  53.     end
  54.  
  55.     -- check from last to first, i.e. backwards
  56.     for index = math.min(#str,maxLength),1,-1 do
  57.         local char = str:sub(index,index)
  58.  
  59.         if char == " " and index > 3 then
  60.             pre = str:sub(1,index-1)
  61.             post = str:sub(index+1,-1)
  62.             return pre, post
  63.         end
  64.     end
  65.    
  66.     return pre, post
  67. end
  68.  
  69. -- eof
RAW Paste Data