---
name: utf8
last_updated: 2026-12-04T23:21:36Z
type: library
summary: "This library provides basic support for `UTF-8` encoding."
---

# utf8

This library provides basic support for `UTF-8` encoding.

**Type:** library

## Description

This library provides basic support for `UTF-8` encoding. This library does
not provide any support for Unicode other than the handling of the encoding.
Any operation that needs the meaning of a character, such as character
classification, is outside its scope.

Unless stated otherwise, all functions that expect a byte position as a
parameter assume that the given position is either the start of a byte
sequence or one plus the length of the subject string. As in the string
library, negative indices count from the end of the string.

You can find a large catalog of usable `UTF-8` characters
[here](https://www.w3schools.com/charsets/ref_html_utf8.asp).

## Properties

### utf8.charpattern

**Type:** `string`

The pattern `"[%z\x01-\x7F\xC2-\xF4][\x80-\xBF]*"`, which matches exactly
zero or more UTF-8 byte sequence, assuming that the subject is a valid
UTF-8 string.

**Utf8 Charpattern**

Demonstrates the `utf8.charpattern` property.

```lua
-- Iterate over each UTF-8 character as its own string
local text = "añ€"
local characters = {}
for character in string.gmatch(text, utf8.charpattern) do
	table.insert(characters, character)
end
print(#characters) --> 3
print(#text) --> 6 (bytes)

-- Multi-byte characters stay intact
print(#characters[2], #characters[3]) --> 2 3
```

## Functions

### utf8.char

**Signature:** `utf8.char(codepoints: Tuple<int>): string`

Receives zero or more codepoints as integers, converts each one to its
corresponding UTF-8 byte sequence and returns a string with the
concatenation of all these sequences.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `codepoints` | `Tuple<int>` |  | Zero or more integer codepoints in the range `[0, 0x10ffff]` to encode. |

**Returns:** `string` — A string containing the concatenated UTF-8 byte sequences for each
codepoint.

**Utf8 Char**

Demonstrates the `utf8.char` function.

```lua
print(utf8.char(72, 105)) --> Hi
print(utf8.char(233)) --> é
print(utf8.char(0x20AC)) --> €

-- Multi-byte codepoints produce multi-byte strings
print(#utf8.char(0x20AC)) --> 3

-- Zero codepoints give an empty string
print(utf8.char() == "") --> true
```

### utf8.codes

**Signature:** `utf8.codes(str: string): function, string, int`

Returns an iterator function that iterates over all codepoints in string
`str`, yielding each one's byte position and codepoint. It raises an error
if it meets any invalid byte sequence.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `str` | `string` |  | The string to iterate over. |

**Returns:** `function`, `string`, `int` — The iterator function that, on each call, returns the byte position
and codepoint of the next character. The input string (passed as the invariant state to the iterator). The initial control value (`0`) for the iterator.

**Utf8 Codes**

Demonstrates the `utf8.codes` function.

```lua
local str = "héllo"
for position, codepoint in utf8.codes(str) do
	print(position, codepoint)
end
--> 1 104
--> 2 233
--> 4 108
--> 5 108
--> 6 111

-- Invalid byte sequences raise an error
local ok = pcall(function()
	for _ in utf8.codes("\xff") do
	end
end)
print(ok) --> false
```

### utf8.codepoint

**Signature:** `utf8.codepoint(str: string, i?: int, j?: int): Tuple<int>`

Returns the codepoints (as integers) from all codepoints in the provided
string (`str`) that start between byte positions `i` and `j` (both
included). The default for `i` is `1` and for `j` is `i`. It raises an
error if it meets any invalid byte sequence.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `str` | `string` |  | The UTF-8 encoded string to extract codepoints from. |
| `i` | `int` | `1` | The byte position at which to start reading codepoints. |
| `j` | `int` | `i` | The last byte position at which a codepoint may start. If excluded, this defaults to the value of `i`, so a single codepoint is returned. |

**Returns:** `Tuple<int>` — The codepoints as integers for all characters that start between byte
positions `i` and `j`.

**Utf8 Codepoint**

Demonstrates the `utf8.codepoint` function.

```lua
print(utf8.codepoint("héllo")) --> 104

-- Byte positions i through j are inclusive
print(utf8.codepoint("héllo", 1, 2)) --> 104 233

-- Negative positions count from the end
print(utf8.codepoint("héllo", -1)) --> 111

-- Collect every codepoint in a string
local codepoints = {utf8.codepoint("héllo", 1, -1)}
print(#codepoints) --> 5
```

### utf8.len

**Signature:** `utf8.len(s: string, i?: int, j?: int): int`

Returns the number of UTF-8 codepoints in the string `s` that start
between byte positions `i` and `j` (both inclusive). The default for `i`
is `1` and for `j` is `-1`. If it finds any invalid byte sequence, returns
a nil value plus the position of the first invalid byte.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `s` | `string` |  | The UTF-8 encoded string to measure. |
| `i` | `int` | `1` | The byte position at which to start counting. |
| `j` | `int` | `-1` | The last byte position at which a codepoint may start. |

**Returns:** `int` — The number of UTF-8 codepoints in the specified range, or `nil`
followed by the byte position of the first invalid byte sequence.

**Utf8 Len**

Demonstrates the `utf8.len` function.

```lua
local str = "héllo"
print(#str) --> 6 (bytes)
print(utf8.len(str)) --> 5 (characters)

-- Count from a byte position (must start a character)
print(utf8.len(str, 4)) --> 3

-- Invalid sequences return nil and the position of the first invalid byte
print(utf8.len("ab\xffcd")) --> nil 3
```

### utf8.offset

**Signature:** `utf8.offset(s: string, n: int, i?: int): int?`

Returns the position (in bytes) where the encoding of the `n`‑th codepoint
of `s` (counting from byte position `i`) starts. A negative `n` gets
characters before position `i`. The default for `i` is `1` when `n` is
non-negative and `#s + 1` otherwise, so that `utf8.offset(s, -n)` gets the
offset of the `n`‑th character from the end of the string. If the
specified character is neither in the subject nor right after its end, the
function returns `nil`.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `s` | `string` |  | The UTF-8 encoded string to search within. |
| `n` | `int` |  | The character offset to seek. Positive values count forward, negative values count backward, and `0` finds the start of the character at byte position `i`. |
| `i` | `int` | `1` | The byte position from which to start counting. Defaults to `1` when `n` is non-negative and `#s + 1` when `n` is negative. |

**Returns:** `int?` — The byte position where the target codepoint begins, or `nil` if the
character is not within the string.

**Utf8 Offset**

Demonstrates the `utf8.offset` function.

```lua
local str = "héllo"
print(utf8.offset(str, 3)) --> 4 (third character starts at byte 4)

-- Negative n counts from the end
print(utf8.offset(str, -1)) --> 6

-- n = 0 finds the start of the character containing byte i
print(utf8.offset(str, 0, 3)) --> 2

-- Characters beyond the string return nil
print(utf8.offset(str, 10)) --> nil

-- Slice off the first two characters
print(string.sub(str, utf8.offset(str, 3))) --> llo
```

### utf8.graphemes

**Signature:** `utf8.graphemes(str: string, i: number, j: number): function`

Returns an iterator function that iterates the grapheme clusters of the
string, yielding the first and last byte position of each cluster.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `str` | `string` |  | The UTF-8 encoded string to iterate over for grapheme clusters. |
| `i` | `number` |  | The starting byte position within the string. Negative values count from the end. |
| `j` | `number` |  | The ending byte position within the string. Negative values count from the end. |

**Returns:** `function` — An iterator function that returns the start and end byte positions of
each grapheme cluster.

**Utf8 Graphemes**

Demonstrates the `utf8.graphemes` function.

```lua
-- "e" followed by a combining acute accent is one grapheme but two codepoints
local str = "ae\u{0301}b"
print(utf8.len(str)) --> 4

for first, last in utf8.graphemes(str) do
	local grapheme = string.sub(str, first, last)
	print(first, last, #grapheme)
end
--> 1 1 1
--> 2 4 3
--> 5 5 1
```

### utf8.nfcnormalize

**Signature:** `utf8.nfcnormalize(str: string): string`

Converts the input string to Normal Form C, which tries to convert
decomposed characters into composed characters.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `str` | `string` |  | The UTF-8 encoded string to normalize. |

**Returns:** `string` — The NFC-normalized string with decomposed characters composed into
their precomposed equivalents.

**Utf8 NFC Normalize**

Demonstrates the `utf8.nfcnormalize` function.

```lua
local decomposed = "e\u{0301}" -- "e" plus a combining acute accent
local composed = utf8.nfcnormalize(decomposed)

print(utf8.len(decomposed)) --> 2
print(utf8.len(composed)) --> 1
print(composed == "\u{00E9}") --> true
```

### utf8.nfdnormalize

**Signature:** `utf8.nfdnormalize(str: string): string`

Converts the input string to Normal Form D, which tries to break up
composed characters into decomposed characters.

**Parameters:**

| Name | Type | Default | Description |
|------|------|---------|-------------|
| `str` | `string` |  | The string to convert. |

**Returns:** `string` — The NFD-normalized string with precomposed characters decomposed into
their component parts.

**Utf8 NFD Normalize**

Demonstrates the `utf8.nfdnormalize` function.

```lua
local composed = "\u{00E9}" -- precomposed "é"
local decomposed = utf8.nfdnormalize(composed)

print(utf8.len(composed)) --> 1
print(utf8.len(decomposed)) --> 2
print(decomposed == "e\u{0301}") --> true
```