3

Can we pass 2D array in vardef? Followed is a small code. It failed to compile.

outputtemplate := "%j-%c.eps";
prologues := 3;
input boxes

beginfig(1)

vardef table (expr upper_left_centre, row, col, data) =
  label(data[0][0], upper_left_centre);
enddef;

string data[][];
% title
data[0][0] := "Wall height";

table (origin, 2, 6, data);

endfig;
5

For this, you can declare this array as a suffix parameter.

outputtemplate := "%j-%c.eps";
prologues := 3;

beginfig(1)

vardef table (expr upper_left_centre)(suffix data) =
  label(data[0][0], upper_left_centre);
enddef;

string data[][];
% title
data[0][0] := "Wall height";

table (origin, data);

endfig;

end.

enter image description here

Quoting the MetaPost manual, p. 56:

If you just want to pass a variable name to a macro, it is better to declare it as a suffix parameter. For example,

def incr(suffix $) = begingroup $:=$+1; $ endgroup enddef;

defines a macro that will take any numeric variable, add one to it, and return the new value.

|improve this answer|||||
  • Read the manual many times but ignore the point "Text parameters are very general, but their generality sometimes gets in the way. If you just want to pass a variable name to a macro, it is better to declare it as a suffix parameter.". But the suffix generally makes me confusing. I don't know when I should use. Sometimes by guess. Thanks @ Franck – warem Dec 16 '17 at 20:24
  • Indeed it can ben confusing. I reckon thatsuffix is to be used when you need to manipulate a variable (or more generally a suffix name), e.g. to increment it if it is a numeric. The parameters given as expr are to be used as such, they can't be changed. – Franck Pastor Dec 16 '17 at 21:29
  • 1
    The difference is in the expansion. expr variables are expanded before they are passed to the macro. text and suffix are not. suffix has a limited range of allowed characters, text is more general, with for example, , allowed. – Thruston Dec 17 '17 at 17:11
  • @Thruston Thanks for this. It is much clearer than the MetaPost manual's explanations! :-) – Franck Pastor Dec 17 '17 at 21:15

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.