Codectionary / Developer documentation / Lua

Lua UTF-8 code-point iteration

Lua 5.3+ utf8.codes produces Unicode code points with their starting byte positions. Ordinary string lengths and offsets still count bytes.

Syntax

for bytePosition, codePoint in utf8.codes(text) do ... end

Examples

Lua UTF-8 code-point iteration

Run with standalone Lua 5.4: lua example.lua. These scripts target Lua 5.4 rather than Roblox Luau.

local text = "A" .. utf8.char(0xE9)
print(#text, utf8.len(text))
for position, code in utf8.codes(text) do print(position, code) end
  1. Output pairs: 3 and 2; 1 and 65; 2 and 233. The accented character occupies two bytes but one code point.

Best practices

  • Validate malformed UTF-8 before iteration for untrusted input. Code points are not necessarily user-visible grapheme clusters.

Runtime & versions

Lua interpreter or a host application. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Lua reference manuals

Specifications & further reading