
我在嘗試對多部分節點使用計算值時出現了一些奇怪的行為。有時值不可用(我收到未定義的控制序列錯誤)。
這是一個 MWE:
\documentclass[border=1mm] {standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcsb}[2]{
\pgfmathsetmacro\calcOne{ #2 / #1 }
\pgfmathsetmacro\calcTwo{ \calcOne + #1 }
\node (d0)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (0,0)
{Detail 0%
\nodepart{two}\calcOne
\nodepart{three}\calcTwo
};
}
\newcommand{\splitcalcs}[2]{
\def\calcOne{\fpeval { #2 / #1 }}
\def\calcTwo{\fpeval{ #2 / #1 + #1 }}
% Uncomment these two lines to get proper functioning
% \global\let\calcOne=\calcOne
% \global\let\calcTwo=\calcTwo
\nodepart{two}\calcOne
\nodepart{three}\calcTwo
}
\begin{document}
\begin{tikzpicture}
%Uncomment only this line to avoid an error but Detail 1 uses the results of this macro call
%\splitcalcsb{3}{1}
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail 1%
\splitcalcs{8}{4}
};
\splitcalcsb{9}{4}
\end{tikzpicture}
\end{document}
如果我取消註釋該\splitcalcsb{3}{1}
行,則不再觸發錯誤,但我得到以下圖像:
而Detail 1的內容反映的是\splictcalcsb{3}{1}
呼叫的計算而不是\splitcalcs{8}{4}
呼叫。
如果我取消註釋這些\global\let
行,一切都會正常工作,但我真的想避免創建\global
定義。
有誰知道一種方法(a)用於在巨集中定義中間計算,以及(b)在來自同一宏的呼叫\pgfmathsetmacro
中使用這些計算的結果而不使用全域變數?\nodepart
答案1
@egreg 在回答類似問題時展示瞭如何做到這一點。
使用\noexpand
和\expanded
。
\documentclass[border=1mm] {standalone}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcs}[2]{
\pgfmathsetmacro\calcOne{ #2 / #1 }
\pgfmathsetmacro\calcTwo{ \calcOne + #1 }
\expanded{%
\noexpand\nodepart{two} \calcOne
\noexpand\nodepart{three} \calcTwo
}%
}
\begin{document}
\begin{tikzpicture}
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail 1%
\splitcalcs{8}{4}
};
\end{tikzpicture}
\end{document}