-- util.lua
function tcontains(t,element)
for _,value in pairs(t) do
if element == value then
return true
end
end
return false
end
function wordwrap(str, callback, maxLength, maxRows)
if type(callback) == "table" then
local t = callback
callback = function(row) table.insert(t, row) end
end
local rows = 0
while #str > 1 do
if type(maxRows) == "number"
and rows >= maxRows and (#str + 3 > maxLength) then
callback(str:sub(1,maxLength-3) .. "...")
return str
else
local pre = ""
pre, str = smartSplit(str, maxLength)
callback(pre)
rows = rows + 1
end
end
return nil
end
-- split a string at a space if possible
function smartSplit(str, maxLength)
if #str < maxLength then
return str, ""
end
local pre = str:sub(1,maxLength)
local post = str:sub(maxLength+1,-1)
-- check from first to last
for index = 1,math.min(#str,maxLength) do
local char = str:sub(index,index)
if char == "\n" then
pre = str:sub(1,index-1)
post = str:sub(index+1,-1)
return pre, post
end
end
-- check from last to first, i.e. backwards
for index = math.min(#str,maxLength),1,-1 do
local char = str:sub(index,index)
if char == " " and index > 3 then
pre = str:sub(1,index-1)
post = str:sub(index+1,-1)
return pre, post
end
end
return pre, post
end
-- eof
Comments