[metapost] accessing variables in nested macros

Stephan Hennig mailing_list at arcor.de
Sat Feb 10 15:39:26 CET 2007

Piotr Zielinski schrieb:
> On 09/02/07, Stephan Hennig <mailing_list at arcor.de> wrote:
>> when called, more or less to literally replace "init;" by
>> "calculation;" and therefore accessing variables from "calcA" in
>> "init" should be ok.
> The problem is that "parameters" is not a variable but a parameter. 
> These two are very different concepts in Metapost.
> [...]
> As opposed to variables, which are expanded "on-demand", parameters
> are expanded "in advance". When metapost encounters "calcA(5)" it 
> replaces it with its definition (in your case "begingroup init; 
> endgroup") with all occurrences of "parameters" replaced by "5". Note
> that these substitutions are done when "calcA(5)" is expanded,
> before any of its code starts "executing", and are done only within
> the body of "calcA".

Thanks a lot!  My MetaPost world is in order, again.  The solution for
my problem is just to parametrize "init".  I can live with that.

Sounds like I really have to take a closer look at the original
MetaFont.  On the other hand, this information is obviously missing from
mpman.  It would be nice if something along your lines could be added to
the manual.

> Note that since parameter substitution is purely textual, you don't 
> have to tell Metapost anything about the type of "parameters" (as you
> would have if "parameters" were a variable).

One additional observation: At least, arguments seem to be evaluated
before substitution and operations involving a parameter are magically
chosen sensibly.  The code

def calcA(expr a)=

  show calcA(5+5);

returns 20.  One could equally well expect the result to be

15=2*5+5        or
30=25+5         or
210 (2 and 10)

for a purely textual substitution.  How is the implicit binary operation
(multiplication) preserved when "a" isn't a variable with a known type

> The same applies to a "for" loop in Metapost.  The following code
> for i = 1 upto 5: blah i blah  endfor
> is textually expanded, and exactly equivalent to
> blah 1 blah blah 2 blah blah 3 blah blah 4 blah blah 5 blah
> At no point does a variable named "i" exist.

That's very interesting.  The for loop doesn't interfere with an already
declared variable i, that is, the value of i is preserved.  This fact is
missing from mpman, too.

> IMHO understanding that, unlike other languages, Metapost does most of
> its work by textual substitution is crucial to understand the quirks
> (and power) of the language.

Unfortunately, mpman doesn't work that out, yet.

> Knuth's "MetaFONTbook" is an excellent source of information.

That goes without saying for all of his books.  But, how did he write
those pieces of software thirty years ago about which you can learn
something new every day?  Just because he wanted to get a formula printed!

Best regards,
Stephan Hennig

More information about the metapost mailing list