Advertisement
HugoBDesigner

Fixed printf

Mar 15th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.71 KB | None | 0 0
  1. function printf(t, x, y, w, l, a)
  2.     t = string.gsub(t, "\r\n", "\n")
  3.     local font = love.graphics.getFont()
  4.     local ret = {t}
  5.     local spacesplit = {}
  6.     local lineskip = 0
  7.     local align = a or "left"
  8.    
  9.     for i = string.len(ret[#ret]), 1, -1 do
  10.         local v = string.sub(ret[#ret], i, i)
  11.         if v == "\n" then
  12.             lineskip = lineskip+1
  13.         end
  14.     end
  15.    
  16.     local TEST = 0
  17.     while font:getWidth(ret[#ret]) > w or lineskip > 0 do
  18.         TEST = TEST + 1
  19.         local nn = false
  20.         local skip = 0
  21.         for i = 1, string.len(ret[#ret]) do
  22.             local v = string.sub(ret[#ret], i, i)
  23.             if v == " " then
  24.                 if font:getWidth(string.sub(ret[#ret], 1, i-1)) <= w then
  25.                     nn = i
  26.                     skip = 0
  27.                 end
  28.             end
  29.            
  30.             if v == "\n" and font:getWidth(string.sub(ret[#ret], 1, i-1)) <= w then
  31.                 nn = i
  32.                 lineskip = lineskip-1
  33.                 break
  34.             end
  35.         end
  36.        
  37.         if not nn then
  38.             for i = 1, string.len(ret[#ret]) do
  39.                 if font:getWidth(string.sub(ret[#ret], 1, i)) <= w then
  40.                     nn = i
  41.                 else
  42.                     break
  43.                 end
  44.             end
  45.         end
  46.        
  47.         table.insert(ret, string.sub(ret[#ret], nn+1, -1))
  48.         ret[#ret-1] = string.sub(ret[#ret-1], 1, nn-skip)
  49.     end
  50.    
  51.     if l then
  52.         local rem = false
  53.         while #ret > l do
  54.             rem = true
  55.             table.remove(ret)
  56.         end
  57.         local r = "..."
  58.         if rem then
  59.             local off = 1
  60.             if font:getWidth(ret[#ret] .. r .. " ") > w then
  61.                 off = string.len(r)+1
  62.             end
  63.             ret[#ret] = string.sub(ret[#ret], 1, -off) .. "..."
  64.         end
  65.     end
  66.    
  67.     for i, v in ipairs(ret) do
  68.         local xx = x
  69.         if align == "right" then
  70.             xx = x-font:getWidth(string.gsub(v, "\n", ""))
  71.         elseif align == "center" then
  72.             xx = x-font:getWidth(string.gsub(v, "\n", ""))/2
  73.         end
  74.         love.graphics.print(string.gsub(v, "\n", ""), xx, y+(i-1)*font:getHeight())
  75.     end
  76. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement