29.11.2012 Views

MetaFun - Pragma ADE

MetaFun - Pragma ADE

MetaFun - Pragma ADE

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

vardef spring (expr a, b, w, h, n) =<br />

pair vec ; path pat ; numeric len ; numeric ang ;<br />

vec := (b-a) ;<br />

pat := for i=1 upto n-1: (if odd(i):-fi w/2,i)--endfor (0,n) ;<br />

pat := (0,0)--(0,h)-- pat shifted (0,h)--(0,n+h)--(0,n+2h) ;<br />

len := (xpart vec ++ ypart vec)/(n+2h) ;<br />

ang := -90+angle(vec) ;<br />

( pat yscaled len rotatedaround(origin,ang) shifted a )<br />

enddef ;<br />

If you use vardef, then the last statement is the return value. Here, when p := spring (z1,<br />

z2, .75cm, 2, 10) is being parsed, the macro is expanded, the variables are kept invisible for<br />

the assignment, and the path at the end is considered to be the return value. In a def the whole<br />

body of the macro is ‘pasted' in the text, while in a vardef only the last line is visible. We will<br />

demonstrate this with a simple example.<br />

def one = (n,n) ; n := n+1 ; enddef ;<br />

def two = n := n + 1 ; (n,n) enddef ;<br />

Now, when we say:<br />

pair a, b ; numeric n ; n= 10 ; a := one ; b := two ;<br />

we definitely get an error message. This is because, when macro two is expanded, METAPOST sees<br />

something:<br />

b := n := n + 1 ;<br />

By changing the second definition in<br />

vardef two = n := n + 1 ; (n,n) enddef ;<br />

the increment is expanded out of sight for b := and the pair (n,n) is returned.<br />

We can draw a slightly better looking spring by drawing twice with a different pen. The following<br />

commands use the spring macro implemented by the vardef.<br />

path p ; p :=<br />

(0,0)--spring((.5cm,0),(2.5cm,0),.5cm,0,10)--(3cm,0) ;<br />

draw p withpen pencircle scaled 2pt ;<br />

draw p withpen pencircle scaled 1pt withcolor .8white;<br />

This time we get:<br />

Since the spring macro returns a path, you can do whatever is possible with a path, like drawing<br />

an arrow:<br />

Simple drawings A few applications<br />

273

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!