ConTeXt and Lua programming/Dimensions

Unofficial ConTeXt Wiki mirror

Last modified: 2025-01-15


NOTE: This article is about the data type. For the names of a page's many dimensions, see Layout parameters and dimensions.

A dimension, in TeX, is a variable storing a length. The length is entered as a number immediately followed by two letters that indicate the unit, e.g. 12pt or 1cm. TeX and MetaPost recognize 9 different units:

The various conversions between the units are laid out in the conversion table at the end of this article.

Defining and accessing dimensions

\newdimen is the native TeX method to initialise a dimension variable. The requirement to explicitly initialize your dimension variables is a bit clunky, but this method should still be preferred over storing dimensions as strings.

The following example shows how to set and access dimensions:

Defining and accessing dimensions in Lua

How to rewrite TeX code

\the\dimexpr\availablehsize\relax %say, 426pt

Mostly LMTX:

Converting dimensions

Usually, you will want to express a dimension in something other than points or scaled points. For this, Lua is the way to go:

Calculating with dimensions

From TeX, you can compute with dimensions by writing your calculation between \dimexpr...\relax. Such an expression may only occur where a length is expected. Spaces are allowed, but never required.

In Lua, dimensions are a number of scaled points, and you can do all the usual things. TeX uses integers for dimens, but Lua treats them as floats; the number will only be coerced to integer when you retrieve from, or assign to, tex.dimen.somevalue. Not that half a scaled point is much to worry about.

More examples

Storing dimensions as strings

Because TeX expands macros, we can store a dimension string like 10pt in a macro, and insert that in any place TeX expects a dimension. You can use a plain \def; or you can define dimensions with \definemeasure[...] and retrieve them with \measure{...}.

Get the height or width of some text

Source

Conversion table

Bold numbers indicate conversions that are set by definition.

unit TeX name in sp in pt in pc in dd in cc in bp in in in mm in cm
scaled point sp 1 1/65536
point pt 65536 1 1/12 0.9346 0.0779 0.9963 1/72.27 0.3516 0.0351
pica pc 786432 12 1 11.2149 0.9346 11.9552 0.1660 4.2175 0.4218
didot dd 70124.081 1.0700 0.0892 1 1/12 1.0660 0.0148 0.3761 0.0376
cicero cc 841488.98 12.8401 1.0700 12 1 12.7921 0.1777 4.5128 0.45128
big point bp 65781.76 1.0038 0.0836 0.9381 0.0782 1 1/72 0.3528 0.0353
inch in 4736286.7 72.27 6.0225 67.5415 5.6284 72 1 25.4 2.54
millimeter mm 186467.98 2.8453 0.2371 2.6591 0.2216 2.8346 0.0394 1 0.1
centimeter cm 1864679.8 28.4528 2.3711 26.5911 2.2159 28.3464 0.39370 10 1

See also