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
| Type | Name | Description |
|---|---|---|
string | input | String to read from |
int | char_at | Character position to look up - negative counts from end |
int | offset | When given - char_at is treated as a byte position, and this many characters are skipped from there |
Returns
| Type | Name | Description |
|---|---|---|
int | nil | position | Byte position of the resulting character, or nil if out of range |
int | nil | codepoint | Codepoint of the resulting character, or nil if out of range |
Examples
local pos, code = util.string.charpos("hello", 1)
core.engine.print("info", pos, code) -- 1 104local pos, code = util.string.charpos("hello", -1)
core.engine.print("info", pos, code) -- 5 111local pos, code = util.string.charpos("a€b", 2)
core.engine.print("info", pos, code) -- 2 8364-- 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