最近我遇到了很多问题,宏在意想不到的时间扩展(或不扩展),所以我以为我在这里遇到了一个相关的问题。但是,在这种情况下,在环境之外,一切都按我想要的方式运行\tabular
。这是一个测试用例:
\documentclass{article}
\usepackage{xparse}
\usepackage{xcolor}
\newcommand{\MyValue}{0}
\newcommand{\PrintMyValue}{\MyValue}
%\NewDocumentCommand{\ShowMyValue}{}{ % Same results
%\newcommand{\ShowMyValue} { % Same results
\DeclareExpandableDocumentCommand{\ShowMyValue}{}{
\textcolor{red}{\MyValue}
\renewcommand{\MyValue}{0}
}
\begin{document}
\renewcommand{\MyValue}{5}
\PrintMyValue, \ShowMyValue \par % should be 5
\PrintMyValue, \ShowMyValue \par % should be 0
\renewcommand{\MyValue}{7}
\PrintMyValue, \ShowMyValue \par % should be 7
\hrule
\renewcommand{\MyValue}{5}
\begin{tabular}{r l}
\PrintMyValue, &\ShowMyValue \\ % should be 5
\PrintMyValue, &\ShowMyValue \\ % should be 0
\renewcommand{\MyValue}{7}
\PrintMyValue, &\ShowMyValue % should be 7
\end{tabular}
\end{document}
在表格之外,这会产生所需的结果:
5, 5
0, 0
7, 7
但在表格内部,这会产生
5,5
5,5
7,5
我认为这可能与分组有关,但事实似乎并非如此。而且,在 中align*
,相同的代码序列会产生:
5,5
5,5
7,7
答案1
如前所述,每个表格单元格都在其自己的组中进行处理。在您的示例中,您可以改用计数器,并使用\setcounter
它默认全局更改计数器:
\documentclass{article}
\usepackage{xcolor}
\newcounter{MyValue}
%\setcounter{\MyValue}{0}% Already 0 by default
\newcommand{\PrintMyValue}{\theMyValue}
\newcommand{\ShowMyValue}{%
\textcolor{red}{\theMyValue}%
\setcounter{MyValue}{0}% global
}
\begin{document}
\setcounter{MyValue}{5}
\PrintMyValue, \ShowMyValue \par % is 5
\PrintMyValue, \ShowMyValue \par % is 0
\setcounter{MyValue}{7}
\PrintMyValue, \ShowMyValue \par % is 7
\hrule
\setcounter{MyValue}{5}
\begin{tabular}{r l}
\PrintMyValue, &\ShowMyValue \\ % should be 5
\PrintMyValue, &\ShowMyValue \\ % should be 0
\setcounter{MyValue}{7}%
\PrintMyValue, &\ShowMyValue % should be 7
\end{tabular}
\end{document}
答案2
在表格单元格中,所有内容都是本地的,因此对宏的更改是不是在单元格外部识别。\gdef\MyValue{0}
在\renewcommand
表格和宏定义中使用ShowMyValue