# Macro behaviour different inside tabular environment

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

-

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}

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

-
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 4 '11 at 7:04

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

-