util.string.offset

Shared

Converts a character offset into a byte position


Syntax

local position = util.string.offset(
    input,
    count,
    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 read from
intcountNumber of characters to move - positive moves forward, negative moves backward, zero snaps to the start of the current character
intstart_atByte position to move from - defaults to the start when count >= 0, or the end when count < 0

Returns

TypeNameDescription
int | nilpositionResulting byte position, or nil if there is no such character

Examples

Find the byte position of the 3rd character
local pos = util.string.offset("hello", 3)

core.engine.print("info", pos) -- 3
Move forward from a given byte position
local pos = util.string.offset("hello", 2, 2)

core.engine.print("info", pos) -- 4
Move backward from the end of the string
local pos = util.string.offset("hello", -1)

core.engine.print("info", pos) -- 5
Snap to the start of the character containing a byte position
local pos = util.string.offset("a€b", 0, 3)

core.engine.print("info", pos) -- 2 (start of the multi-byte '€')
Returns nil when there is no such character
local pos = util.string.offset("hi", 5)

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

On this page