util.string.invalidoffset

Shared

Finds the byte position of the first invalid UTF-8 sequence


Syntax

local position = util.string.invalidoffset(
    input,
    start_at = nil
)

This function returns a byte position, not a character position.

Passing that position into util.string.sub or util.string.byte - which now index by character will give incorrect results except by coincidence on pure-ASCII input.

Parameters

TypeNameDescription
stringinputString to scan
intstart_atByte position to begin scanning from - negative counts from end

Returns

TypeNameDescription
int | nilpositionByte position of the first invalid byte, or nil if input is fully valid from start_at onward

Examples

A valid string returns nil
local pos = util.string.invalidoffset("hello")

core.engine.print("info", pos) -- nil
Find the position of a malformed byte
local pos = util.string.invalidoffset("ab\xFFcd")

core.engine.print("info", pos) -- 3
Scan starting from a later byte position
local pos = util.string.invalidoffset("\xFFab\xFFcd", 2)

core.engine.print("info", pos) -- 4

On this page