如何将数字参数转换为 MetaPost 宏中的文本

How to convert numeric parameter to text in a MetaPost macro

我试图在 MetaPost 宏中连接一些字符串,其中一些来自数字参数。但是,我收到一条错误消息“额外的令牌将被刷新”。

问题的本质在以下片段中:

    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);

使用 str 将数字更改为字符串在宏外有效,但在宏内无效。为什么?

`str' returns 后缀的字符串表示形式,而不是数值。 1是后缀。

  • str 1 有效 ("1") 因为 1 是后缀。
  • str -1 无效,因为没有后缀 -1

但是等等……[1][-1] 都是后缀,str[1] 呈现 "1"(是的,没有 [])和 str[-1][-1]

将整数或浮点数转换为字符串的正确函数是decimal

可以用 str 重新实现 decimal,只是为了好玩:

% 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;