Search code examples
macrosmetapost

How to convert numeric parameter to text in a MetaPost macro


I tried to concatenate some strings in a MetaPost macro where some of them come from numeric parameters. However, I get an error message "Extra tokens will be flushed".

The essence of the problem is in the following snippet:

    def foo(expr a) =
      show a; % this prints 1
      show str a; % this prints "" and crashes
    enddef;
    
    show str 1; % this prints "1"
    foo(1);

Changing number to string with str works outside macro but not inside the macro. Why?


Solution

  • `str' returns the string representation of a suffix, not the numeric value. 1 is the suffix.

    • str 1 is valid ("1") because 1 is a suffix.
    • str -1 is invalid because there is no suffix -1

    but wait… both [1] and [-1] are suffixes, str[1] renders "1" (yes, without []) and str[-1] is [-1]

    The proper function to convert integer or float to string is decimal.

    It is possible to reimplement decimal with str, just for fun:

    % Integer to string without decimal
    vardef funny_decimal(expr num) = 
       save s; string s; s=str[num]; % [] needed to evaluate num
       if substring(0,1) of s = "[":
          substring (1,length(s)-1) of s
       else:
          s
       fi
    enddef;