3

Why can't I use variable names like a1, str2, x12? Does Metapost consider them as arrays so that a1 is like a[1] and so on? Even z-notation as z1, z2 and etc. does not work.

The code is

beginfig(1);
# := 5mm;
pair z1, z2, z3, z4;
z1 = (10#, #);
z2 = (#, 12#);
z3 = origin;
z4 = (11#, 13#);
draw z1--z2;
draw z3--z4;
endfig;
end;
bye.

The error is as follows:

! Illegal suffix of declared variable will be flushed.
<to be read again>
                   1
l.153 pair z1
             , z2, z3, z4;
?
1
  • @campa Well, I've commented the declaration and there is no any errors with compilation. I thought only numeric variables did not need to be explicitly declared...
    – Vladimir
    Oct 13, 2021 at 11:47

1 Answer 1

3

There are a couple of points here.

First you can't put a suffix in a variable declaration. Instead you have to declare them collectively. So this works:

prologues := 3;
outputtemplate := "%j%c.eps";
beginfig(1);
# := 5mm;
pair p[];
p1 = (10#, #);
p2 = (#, 12#);
p3 = origin;
p4 = (11#, 13#);
draw p1--p2;
draw p3--p4;
endfig;
end

Secondly, you can't use the variable declaration z[] with plain MP because of a special case. If you try this:

prologues := 3;
outputtemplate := "%j%c.eps";
beginfig(1);
# := 5mm;
pair z[];
z1 = (10#, #);
z2 = (#, 12#);
z3 = origin;
z4 = (11#, 13#);
draw z1--z2;
draw z3--z4;
endfig;
end

you will get this error

! Declared variable conflicts with previous vardef.
<to be read again> 
                   ;
l.5 pair z[];

because plain.mp has a clever macro defined called z that allows you to use z1, z2, z3, etc as pairs without any explicit declaration. So, as the OP discovered, this also works:

prologues := 3;
outputtemplate := "%j%c.eps";
beginfig(1);
# := 5mm;
z1 = (10#, #);
z2 = (#, 12#);
z3 = origin;
z4 = (11#, 13#);
draw z1--z2;
draw z3--z4;
endfig;
end

The clever vardef in plain.mp is this:

vardef z@#=(x@#,y@#) enddef;

With this definition, z1 automatically expands to the literal tokens (x1, y1), where x1 and y1 are ordinary numeric variables.

This works because MP lets you equate numeric variables written as literal pairs like this

(a, b) = (3, 4)

And as you have discovered, you do not have to declare numeric variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.