Macros 如何在MetaPost宏中将数值参数转换为文本
我尝试在MetaPost宏中连接一些字符串,其中一些字符串来自数值参数。但是,我收到一条错误消息“额外的令牌将被刷新” 问题的本质在于以下代码片段:Macros 如何在MetaPost宏中将数值参数转换为文本,macros,metapost,Macros,Metapost,我尝试在MetaPost宏中连接一些字符串,其中一些字符串来自数值参数。但是,我收到一条错误消息“额外的令牌将被刷新” 问题的本质在于以下代码片段: def foo(expr a) = show a; % this prints 1 show str a; % this prints "" and crashes enddef; show str 1; % this prints "1" f
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);
将number更改为string with str在宏外部有效,但在宏内部无效。为什么?`str'返回后缀的字符串表示形式,而不是数值。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;