Skip to content

Instantly share code, notes, and snippets.

@airstruck
Created July 13, 2016 18:51
Show Gist options
  • Save airstruck/d84855ced90bc96c7c31b95bf0fa833a to your computer and use it in GitHub Desktop.
Save airstruck/d84855ced90bc96c7c31b95bf0fa833a to your computer and use it in GitHub Desktop.
Love text wrapping
local function wrap (text, limit)
local font = love.graphics.getFont()
local lines = {{ width = 0 }}
local advance = 0
local lastSpaceAdvance = 0
local function append (word, space)
local wordAdvance = font:getWidth(word)
local spaceAdvance = font:getWidth(space)
local words = lines[#lines]
if advance + wordAdvance > limit then
words.width = (words.width or 0) - lastSpaceAdvance
advance = wordAdvance + spaceAdvance
lines[#lines + 1] = { width = advance, word, space }
else
advance = advance + wordAdvance + spaceAdvance
words.width = advance
words[#words + 1] = word
words[#words + 1] = space
end
lastSpaceAdvance = spaceAdvance
end
local function appendFrag (frag, isFirst)
if isFirst then
append(frag, '')
else
local wordAdvance = font:getWidth(frag)
lines[#lines + 1] = { width = wordAdvance, frag }
advance = wordAdvance
end
end
local leadSpace = text:match '^ +'
if leadSpace then
append('', leadSpace)
end
for word, space in text:gmatch '([^ ]+)( *)' do
if word:match '\n' then
local isFirst = true
for frag in (word .. '\n'):gmatch '([^\n]*)\n' do
appendFrag(frag, isFirst)
isFirst = false
end
append('', space)
else
append(word, space)
end
end
return lines
end
@tomzpol3
Copy link

Hi

@tomzpol3
Copy link

hi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment