utils.utf8sub

Returns a substring of a UTF-8 string

Prototype

s = utils.utf8sub (str, start, end)

Description

Returns a substring of the UTF-8 string, starting at index 'start' and ending at index 'end'. Both may be negative to indicate counting from the right. The end point is optional and defaults to -1, which is the entire rest of the string.

For strings where each character has a character code of < 128, the behaviour is identical to string.sub:

utils.utf8sub ("ABCDEF", 2, 3)  --> BC
utils.utf8sub ("ABCDEF", 3)     --> CDEF
utils.utf8sub ("ABCDEF", -1)    --> F
The above examples are straight "ASCII" strings (ie. each byte is < 128), however the behaviour is different to string.sub with UTF-8 strings. For example:

utils.utf8sub (utils.fromhex ("C686C689C69C"), 1, 2)  --> (hex) C686C689
utils.utf8sub (utils.fromhex ("C686C689C69C"), -1, -1)  --> (hex) C69C
For Unicode characters (ie. whose character code is >= 128 and <= 255) then the function calculates the number of bytes that each "Unicode code point" will require, and count each one as a "column".

The supplied string must be valid UTF-8. If not, the function returns nil followed by the byte position in error.

Lua functions

Topics