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
| Type | Name | Description |
|---|---|---|
string | input | String to read from |
int | count | Number of characters to move - positive moves forward, negative moves backward, zero snaps to the start of the current character |
int | start_at | Byte position to move from - defaults to the start when count >= 0, or the end when count < 0 |
Returns
| Type | Name | Description |
|---|---|---|
int | nil | position | Resulting byte position, or nil if there is no such character |
Examples
local pos = util.string.offset("hello", 3)
core.engine.print("info", pos) -- 3local pos = util.string.offset("hello", 2, 2)
core.engine.print("info", pos) -- 4local pos = util.string.offset("hello", -1)
core.engine.print("info", pos) -- 5local pos = util.string.offset("a€b", 0, 3)
core.engine.print("info", pos) -- 2 (start of the multi-byte '€')local pos = util.string.offset("hi", 5)
core.engine.print("info", pos) -- nil