5

I have a lot of problems lately with macros expanding (or not expanding) at unexpected times, so thought I was having a related problem here. But, in this case, things are working as I want outside of the \tabular environment. Here is a test case:

\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}

Outside of tabular, this produces the desired results:

5, 5
0, 0
7, 7

But inside tabular, this produces

5, 5
5, 5
7, 5

I thought perhaps it had to with grouping, but that does not appear to be the case. And, inside an align*, the same code sequence produces:

5, 5
5, 5
7, 7

lockstep
  • 250,273
Peter Grill
  • 223,288

2 Answers2

8

inside a tabular cell everything is local, so changes to macros are not recognized outside the cell. Use \gdef\MyValue{0} instead of \renewcommand in the tabular and in the macro definition of ShowMyValue

3

As already mentioned each tabular cell is processed in its own group. In your example you could use a counter instead and use \setcounter which changes the counter globally by default:

\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}
Martin Scharrer
  • 262,582
  • Thanks. I had tried to use a counter, but must have not been accessing it correctly. This solution also works for align*. – Peter Grill May 04 '11 at 07:04