Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print number of characters in UTF-8 string

Tags:

utf-8

lua

For example:

local a = "Lua"
local u = "Луа"
print(a:len(), u:len())

output:

3   6

How can I output number of characters in utf-8 string?

like image 477
theta Avatar asked Dec 20 '22 23:12

theta


2 Answers

If you need to use Unicode/UTF-8 in Lua, you need to use external libraries, because Lua only works with 8-bit strings. One such library is slnunicode. Example code how to calculate the length of your string:

local unicode = require "unicode"
local utf8 = unicode.utf8

local a = "Lua"
local u = "Луа"
print(utf8.len(a), utf8.len(u)) --> 3    3
like image 185
Michal Kottman Avatar answered Dec 23 '22 13:12

Michal Kottman


In Lua 5.3, you can use utf8.len to get the length of a UTF-8 string:

local a = "Lua"
local u = "Луа"
print(utf8.len(a), utf8.len(u))

Output: 3 3

like image 36
Yu Hao Avatar answered Dec 23 '22 14:12

Yu Hao