util.string.charpos

Shared

Retrieves the byte position and codepoint of a character at a given position


Syntax

local position, codepoint = util.string.charpos(
    input,
    char_at = 1,
    offset = 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
intchar_atCharacter position to look up - negative counts from end
intoffsetWhen given - char_at is treated as a byte position, and this many characters are skipped from there

Returns

TypeNameDescription
int | nilpositionByte position of the resulting character, or nil if out of range
int | nilcodepointCodepoint of the resulting character, or nil if out of range

Examples

Get the byte position and codepoint of a character
local pos, code = util.string.charpos("hello", 1)

core.engine.print("info", pos, code) -- 1  104
Use a negative position to read from the end
local pos, code = util.string.charpos("hello", -1)

core.engine.print("info", pos, code) -- 5  111
Find a multi-byte character's position
local pos, code = util.string.charpos("a€b", 2)

core.engine.print("info", pos, code) -- 2  8364
Move relative to a known byte position
-- Find the character 2 positions after byte 1
local pos, code = util.string.charpos("hello", 1, 2)

core.engine.print("info", pos, code) -- 3  108

On this page