natiny.font.offset_at
Lua
natiny.font.offset_at(font, text, x) -> offset
Returns the byte offset in text nearest to horizontal position x.
Parameters
| Name |
Type |
Description |
font |
number |
Font handle from natiny.font.create |
text |
string |
UTF-8 text of one line |
x |
number |
Distance from the start of the line, in drawing units |
Returns
| Type |
Description |
number |
Byte offset from 0 through #text |
Example
Lua
-- where a click puts the caret
local caret = natiny.font.offset_at(font, line, mouse_x - text_x)
local before = line:sub(1, caret)
local after = line:sub(caret + 1)
natiny.render.text(font, text_x, y, before .. "|" .. after)
Notes
- The offset is a byte count, so
text:sub(1, offset) is the part before
the caret and text:sub(offset + 1) the part after it. It always lands on
a UTF-8 boundary, never inside a character.
- Past the middle of a glyph the answer is the offset after it, which is what
makes a click land where the eye put it.
- One line at a time:
\n ends the search and its byte offset is returned.
Slice the line out first for multi-line text.
- The position accounts for kerning, letter spacing, and tab stops in the
same way as
natiny.font.measure_text.