[metapost] On simulating def with vardef

Nicola nvitacolonna at gmail.com
Wed Jul 1 15:52:59 CEST 2009

In article <nvitacolonna-0E0F27.11505130062009 at news.gmane.org>,
 Nicola <nvitacolonna at gmail.com> wrote:

> Hi,
> I used to think that a vardef behaves like a primary because its 
> replacement text is surrounded by begingroup/endgroup. But, recently, I 
> have tried this:
> def foo = x enddef;
> foo := 1; % Ok, sets x=1
> vardef foovar = endgroup gobbled true x gobble begingroup enddef;
> foovar := 2; % Not ok: ! Improper `:=' will be changed to `='.
> I conclude that the replacement text of a vardef macro is treated as a 
> primary in any case. Is it correct? Is there a way to have a vardef in 
> the left hand side of an assignment in some circumstances?
> For those who are care, what I would like to achieve is something like:
> vardef suffixof prefixof @# =
>    endgroup gobbled true @# gobble begingroup
> enddef;
> vardef prefixof x@# =
>    endgroup gobbled true suffixof #@.@ gobble begingroup
> enddef;
> so that
> prefixof x.a := 0;
> would set x=0 (I know that I can use 'str', but I would like to know if 
> this is possible without it).
> Thanks,
> Nicola
> --
> http://tug.org/metapost/

Ok, I've found a solution by myself. The problem is that

begingroup endgroup gobbled true

expands into an (empty) secondary. So, I cannot see any way in which a 
vardef macro name can (directly) appear as a lhs of an assignment. 
Therefore, my solution introduces a def:

vardef suffixof prefixof @# =
    endgroup @# gobble begingroup
vardef prefixof x@# =
    endgroup gobble suffixof #@.@ gobble begingroup

def assignprefix suffix s = gobble prefixof s enddef;

So, now

assignprefix x.a := 0;

indeed works and it sets x=0 (and so does assignprefix x.a[1].c := 0, or 

Well, for me it was a funny challenge.

More information about the metapost mailing list