Skip to content

Instantly share code, notes, and snippets.

@prapin
Created June 19, 2012 12:41
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 prapin/b0ae016da7b8f0b221ff to your computer and use it in GitHub Desktop.
Save prapin/b0ae016da7b8f0b221ff to your computer and use it in GitHub Desktop.
Trying to write the smaller possible UTF-8 encoder for Lua. The code relies on bit32 library available from Lua 5.2 and backported to Lua 5.1
-- Encode the input number value into a UTF-8 string in Lua 5.2
function utf8(c)
local t,C={},string.char
if c<128 then return C(c) end
for s=1,3 do
if c<2^(5*s+6) then
for i=s*6,0,-6 do
t[#t+1]=128+bit32.extract(c,i,6)
end
t[1]=t[1]+({64,96,112})[s]
return C(table.unpack(t))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment