util.string.widthindex

Shared

Finds the character position where a cumulative display width is reached


Syntax

local index, remaining, char_width = util.string.widthindex(
    input,
    width,
    ambiguous_as_double = false,
    default_width = 0
)

Parameters

TypeNameDescription
stringinputString to measure
intwidthTarget display width to find the cutoff for
boolambiguous_as_doubleWhen true - East Asian "ambiguous width" characters count as double-width instead of single-width
intdefault_widthWidth to use for codepoints with no defined display width

Returns

TypeNameDescription
intindexCharacter index at which the target width is used up
intremainingLeftover width still available within that character - only returned if the budget ran out mid-string
intchar_widthDisplay width of the character at index - only returned if the budget ran out mid-string

Examples

Budget larger than the whole string returns one value
local index = util.string.widthindex("hi", 10)

core.engine.print("info", index) -- 3 (past the end - the whole string fit)
Find a cutoff that lands inside a wide character
local index, remaining, char_width = util.string.widthindex("中文", 1)

core.engine.print("info", index, remaining, char_width) -- 1  1  2
Truncate a string to fit a fixed display width
local text = "hello world"
local index = util.string.widthindex(text, 5)

core.engine.print("info", util.string.sub(text, 1, index)) -- 'hello'

On this page