Class Text
Text layout without drawing, as the global table Text.
Functions
Text.measure(text: string, font: Font, max_width: number?, options: { wrap: boolean? }?) -> TextMetricsmeasure
The size text would have in a DrawableText with the same font. Use it to size a box around a label, or to see where wrapped text breaks.
fontis required.{}is the default font.- Line breaks and tabs count as spaces. Text past 2048 characters is cut.
- Empty text has width 0 and the height of one line.
- With
max_width, wider text is cut with an ellipsis ("…").metrics.textholds what is left, and is empty when even the ellipsis doesn't fit. - With
max_widthandwrap = true, the text breaks into lines instead: between words where it can, inside a word that is too wide on its own.
Errors without a font, and for a font.file that isn't a font.
A label cut to fit on a backing rectangle:
lua
local font = { size = 13, weight = 600 }
local label = "a long window title that will not fit"
local metrics = Text.measure(label, font, 120)
output.drawables = {
Drawable.rect({ left = 8, top = 8, width = math.ceil(metrics.width) + 12, height = math.ceil(metrics.height) + 6, radius = 4, fill = "#3b4252" }),
Drawable.text({ left = 14, top = 11, text = metrics.text, font = font }),
}Cache results for text that is measured often:
lua
local measured = {}
local function measure(text, font, max_width)
local key = font.size .. " " .. font.weight .. " " .. (max_width or "-") .. " " .. text
local metrics = measured[key]
if not metrics then
metrics = Text.measure(text, font, max_width, { wrap = true })
measured[key] = metrics
end
return metrics
end
local lines = measure("two words", { size = 13, weight = 400 }, 40).text