Lua utf8 Library
Lua strings are sequences of bytes, and the string library works byte by byte. That is fine for English text, but in UTF-8 (the standard encoding for text today) characters such as é, ß, € or emoji take 2 to 4 bytes. The utf8 library, added in Lua 5.3, works with characters (Unicode code points) instead.
local word = "café"
print(#word, utf8.len(word))
print(word:upper()) -- string.upper only knows ASCII
print(word:sub(1, 4), word:sub(1, 5)) -- byte positions!5 4
CAFé
caf� café
#word is 5 because é is two bytes. word:sub(1, 4) cuts the é in half, leaving an invalid byte that shows as �.
The functions
| Function | Purpose |
|---|---|
utf8.len(s [, i [, j]]) |
number of characters, or nil plus the position of the first invalid byte |
utf8.char(...) |
build a string from code points |
utf8.codepoint(s [, i [, j]]) |
code points of the characters between byte positions i and j |
utf8.codes(s) |
iterator over (byte position, code point) pairs |
utf8.offset(s, n [, i]) |
byte position where the n-th character starts |
utf8.charpattern |
a pattern matching exactly one UTF-8 character |
Building and inspecting characters
print(utf8.char(72, 233, 108, 108, 246, 8364))
print(utf8.codepoint("€"))
print(utf8.codepoint("Añb", 1, -1))
print("\u{1F319}", #"\u{1F319}") -- crescent moon emoji: 4 bytesHéllö€
8364
65 241 98
🌙 4
Looping over characters
utf8.codes iterates character by character. gmatch with utf8.charpattern gives the characters as strings:
local text = "naïve €5"
for pos, code in utf8.codes(text) do
io.write(string.format("%d:U+%04X ", pos, code))
end
print()
local chars = {}
for ch in text:gmatch(utf8.charpattern) do
chars[#chars + 1] = ch
end
print(#chars, table.concat(chars, "|"))1:U+006E 2:U+0061 3:U+00EF 5:U+0076 6:U+0065 7:U+0020 8:U+20AC 11:U+0035
8 n|a|ï|v|e| |€|5
The byte positions jump from 3 to 5 and from 8 to 11 because ï and € take more than one byte.
Character-based substrings
utf8.offset converts character positions to byte positions, which you can then give to string.sub:
local function usub(s, i, j)
local startByte = utf8.offset(s, i)
local endByte = j and (utf8.offset(s, j + 1) or #s + 1) - 1 or #s
return s:sub(startByte, endByte)
end
local city = "Zürich-Genève"
print(usub(city, 1, 6))
print(usub(city, 8))
print(utf8.offset(city, -1), usub(city, utf8.len(city)))
local function ureverse(s)
local out = {}
for _, c in utf8.codes(s) do table.insert(out, 1, utf8.char(c)) end
return table.concat(out)
end
print(ureverse("añb€"), ("añb€"):reverse() == ureverse("añb€"))Zürich
Genève
15 e
€bña false
string.reverse reverses bytes, which scrambles multi-byte characters; reversing code points keeps them intact.
Validating input
utf8.len returns nil and the position of the first bad byte when a string isn't valid UTF-8, a quick way to check text from files or the network:
local good = "olá"
local bad = "ol\xE1" -- Latin-1 encoded á: invalid in UTF-8
print(utf8.len(good))
print(utf8.len(bad))3
nil 3
What utf8 doesn't do
The library only knows how UTF-8 encodes code points. It has no idea about letters, case or sorting: string.upper("é") stays é, and comparing strings with < orders by bytes. Combined characters (like e + a combining accent, or emoji with skin-tone modifiers) count as several code points. For full Unicode support, applications use libraries such as luautf8 or the host program's text APIs.
Test yourself
What does #"€" return?
- 1
- 2
- 3
- 4
Which function counts characters instead of bytes?
string.lenutf8.len#utf8.count
What does utf8.char(65, 66) return?
"6566""AB"{65, 66}"A"