3

How to get the REAL length of the string with cyrillic symbols in lua?

If i'm using string.len("HELLO.") - I will get 6

But with string.len("ПРИВЕТ") - I will get 12(Same with "#" operator)

So the number of symbols didn't changed, but we got different numbers... It's because cyrillic symbols has two bytes, when english letters, numbers and etc has 1. I want to know how to get the right and real length of string(Get 6 in both samples). Everyone who can help?

2
  • To be clear, a Lua string is a counted sequence of bytes. Some of functions in the string library operate on the assumption that those bytes are text when viewed with respect to the current locale. (Locale includes a character encoding.) Specifically, len and # return the number of bytes in the string, regardless of those bytes being encoded text. Mar 31, 2017 at 0:32
  • 4
    str_len = #('ПРЕВЕД!'):gsub('[\128-\191]', '') Mar 31, 2017 at 12:29

1 Answer 1

5

string.len and # count bytes, not chars.

In Lua 5.3+, use utf8.len.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.