In UTF-8 encoding, the number of bytes received for a character is determined by the first byte of that character, in accordance with the following table (taken from RFC 3629 :
Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
If the most significant bit of the first byte is "0", the character has only one byte. If the most significant bit is "110", the character has 2 bytes, etc.
Then you can read one byte from the file and determine how many remaining bytes you need to read for the full UTF-8 character:
function get_one_utf8_character(file) local c1 = file:read(1) if not c1 then return nil end local ncont if c1:match("[\000-\127]") then ncont = 0 elseif c1:match("[\192-\223]") then ncont = 1 elseif c1:match("[\224-\239]") then ncont = 2 elseif c1:match("[\240-\247]") then ncont = 3 else return nil, "invalid leading byte" end local bytes = { c1 } for i=1,ncont do local ci = file:read(1) if not (ci and ci:match("[\128-\191]")) then return nil, "expected continuation byte" end bytes[
source share