In article <0E2E620E-1148-41AD-9966-54A594FCCE94@xs4all.nl>,
Hans van der Meer
I cannot find the answer to the following question in Knuth's Metafont book. The following definition with a trailing text argument:
def mydef (expr a, b, c) text modifier = if
: else: fi enddef; How can I do the switch on an empty or nonempty modifier argument? It is not a string because calling its length fails with an error.
A text argument is a (more or less) arbitrary sequence of tokens—that is, loosely speaking, any “chunk” of MetaPost code.
I must do the switch, because "fill modifier" with an empty "modifier" gives horrible results.
Usage would be calls like: mydef(1,2,3) withcolor green; % with modifier text mydef(1,2,3); % without modifier text
This is the best I could think of: vardef emptytext?@# text t = (str @# = "empty.sandwich") enddef; def mydef(expr a,b,c) text t = if begingroup emptytext? empty t sandwich endgroup: % t is empty draw unitsquare scaled 1cm; else: % t is not empty fill unitsquare scaled 1cm t ; fi; enddef; The key is the 'emptytext? empty t sandwich;' line: if t is empty, @# matches 'empty.sandwich', otherwise it matches 'empty' possibly followed by something else (depending on what t actually is). The undelimited text parameter of emptytext? is needed to “swallow” whatever tokens are left (possibly none) after matching the implicit suffix parameter. Note that begingroup and endgroup are necessary in the if clause, otherwise emptytext?'s undelimited text parameter will match beyond the colon. In practice, you should rename 'sandwich' to some token that you are pretty sure will never occur as the beginning of the text argument when you invoke mydef. I'd be glad to hear about other solutions: this question has bugged me for some time… Regards, Nicola