util.string.next

Shared

Finds the byte position and codepoint of a character relative to another


Syntax

local position, codepoint = util.string.next(
    input,
    start_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 search within
intstart_atByte position to search from - negative counts from end
intoffsetNumber of characters to move past start_at - defaults to 1 if start_at is given, otherwise 0

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 first character with no arguments
local pos, code = util.string.next("hello")

core.engine.print("info", pos, code) -- 1  104
Get the character right after a given position
local pos, code = util.string.next("hello", 1)

core.engine.print("info", pos, code) -- 2  101
Move multiple characters forward
local pos, code = util.string.next("hello", 1, 3)

core.engine.print("info", pos, code) -- 4  108
Returns nil when moving past the end of the string
local pos, code = util.string.next("hi", 1, 5)

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

On this page