Learn MetaPost

Variables

Variable types

MetaPost uses 10 different types of variables. Here we will have a look at the three most commonly used types:

  1. Numeric

  2. Pair

  3. Path

These three make up the building blocks of most MetaPost figures.

Numeric

A numeric is simply a floating point number. We can declare and initialize a numeric like so

numeric a;
a:=4.0;

For numerics we can actually skip the declaration as MetaPost will automatically create a numeric when we assign a value to it.

Pair

A pair is simply a tuple containing two numerics. Pairs are hugely useful as they describe positions in the 2d coordinate system that is out main reference for locating things in metapost. Lets declared two points A and B like so:

pair A,B;

once declared we can initialize A and B.

A := (1,1);
B := (2,2);

Path

Finally, a path can be defined by a combination of pairs, and instructions for connecting those pairs. A basic connection instruction is the "–" operator, which says to connect pairs using straight lines. Given pairs A, and B we can define a straight line l by writing

path l;
l := A--B;

MetaPost can draw paths using the draw command:

draw l;

Collection of variables

Sometimes we want to declare a collection of variables. We can do that by writing [] after a variable declaration.

pair A[];

A is now an array of pairs, we can address the individual pairs by suffixing A with a number:

pair A[];
A0 := (1,1);
A1 := (2,2);

By default MetaPost declares variables x and y as arrays of numerics and z as an array of pairs. And it maintains the relationship z(suffix)=(x(suffix),y(suffix)). We can use this to skip declarations if we only need a single collection of points in our figure, for example in this figure:

Using point to draw a line.

beginfig(1)
  x1 = y1 = 10;
  x2 = y2 = 20;
  draw (0,y1)--z1--z2--(30,y2);
endfig
end

Exercise

Use variables to draw a line through three points.

Hint

A line through three points.

outputformat := "png";
outputtemplate := "%j.png";
hppp := 0.25;
vppp := 0.25;

beginfig(1);
  z1 = (10,10);
  z2 = (20,30);
  path p;
  p := z1--origin--z2;
  draw p;
endfig
end
Last updated on 2 Apr 2021
Published on 2 Apr 2021