function split(str, delim, plain)
local tokens, pos, plain = {}, 1, not (plain == false)
repeat
local npos, epos = string.find(str, delim, pos, plain)
table.insert(tokens, string.sub(str, pos, npos and npos - 1))
pos = epos and epos + 1
until not pos
return tokens
end
function buildMessage(str, len)
local words, temp, result = split(str, " "), "", {}
for i, word in ipairs(words) do
if temp:len() < len then
if word:len() < (len - temp:len()) then
if temp:sub(#temp, #temp):find("%s") or temp:len() == 0 then
temp = temp .. word
else
temp = temp .. " " .. word
end
else
table.insert(result, temp)
temp = ""
end
end
end
return result
end
local function split_by_lines(str, limit)
local lines = {} -- результат
local line = "" -- текущая временная строка
-- проходим по словам
for word in (str .. " "):gmatch("(.-) ") do
if #line + #word < limit then
line = line .. " " .. word
else
table.insert(lines, line)
line = word
end
-- чистим начальные и замыкающие пробелы,
-- чтобы не было мусора
line = line:match("^%s*(.-)%s*$")
end
-- догоняем хвост
table.insert(lines, line:match("^%s*(.-)%s*$"))
return lines
end
local text = "This is the long long text that should be splitted by lines"
local result = split_by_lines(text, 15)
print( table.concat(result, "\n") )
> This is the
> long long text
> that should be
> splitted by
> lines