Truncating Long UTF-8 Label Text with an Ellipsis in Lua

Long strings can overflow a fixed label. The original project used a SubUTF8String helper to truncate by characters rather than raw bytes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function truncateLabel(text, maxCharacters)
    if text == nil or maxCharacters == nil then
        return nil
    end

    if utf8 and utf8.len and utf8.offset then
        local length = utf8.len(text)
        if length and length > maxCharacters then
            local endByte = utf8.offset(text, maxCharacters + 1)
            return string.sub(text, 1, endByte - 1) .. "..."
        end
        return text
    end

    if string.len(text) > maxCharacters then
        return SubUTF8String(text, maxCharacters) .. "..."
    end
    return text
end

string.len() counts bytes, so it should not be used by itself as a character count for UTF-8 text. For proportional fonts, character count is only an approximation; measuring rendered width and truncating until it fits produces a more accurate UI.