Skip to content

Instantly share code, notes, and snippets.

@moogoo78
Created March 24, 2016 09:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moogoo78/d55c91376228659f3207 to your computer and use it in GitHub Desktop.
Save moogoo78/d55c91376228659f3207 to your computer and use it in GitHub Desktop.
lua truncate multi-byte string
local function truncate(s, n, tail)
local c = 0 -- 判斷字寬, 中文: 2, 西歐字母: 1
local c2 = 0 -- 判斷字元 (中文大部分3byte, TODO)
local add_tail = false
local r = ""
for i in s:gmatch("[\1-\127\194-\244][\128-\191]*") do
if c > n then
add_tail = true
break
end
if string.byte(i) > 127 then
c = c + 2
c2 = c2 + 3
else
c = c + 1
c2 = c2 + 1
end
end
r = string.sub(s, 0, c2)
if add_tail then
if tail == nil then
r = r .. "..."
else
r = r .. tail
end
end
return r
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment