# Converting command to result

Consider this example:

\documentclass{article}

\newcommand{\foo}{}
\newcommand{\currentbar}{\thebar}

\newcounter{bar}
\setcounter{bar}{0}

\makeatletter
\makeatother

\begin{document}

\begin{baz}
\end{baz}

\begin{baz}
\end{baz}

\foo
\end{document}


I have a command named \foo, a counter named bar and an enviroment baz. I would like \foo to store the state of the counter bar at each end environment baz.

At the end of the first baz, bar equals 1, so 1 should be written to \foo. At the end of the second baz, bar equals 2 so \foo should be 12 (2 is concantenated to the already existing 1).

As is, the \foo is most likely actually \currentbar\currentbar, and that outputs 22 when called at the end of the document.

How could I "expand" the \currentbar to 1 and 2 so that \foo would be 12 at the end?

-

You need to expand \currentbar at the moment of adding it to \foo.

The simplest way is to use \xappto from the etoolbox package: instead of \g@addto@macro\foo{\currentbar}, say

\xappto\foo{\currentbar}


Of course \usepackage{etoolbox} in the preamble is needed.

-
You're a lifesaver, egreg :). Something I noticed; apparently \ must be appended with \gappto if one wants to create tabular data that way. –  ipavlic Jun 7 '11 at 15:08
@ipavlic: \gappto is exactly the same as \g@addto@macro and the g stands for "global": environments form a group, so definitions inside them are lost when they are closed, unless the definition is global. If you try texdef -t latex g@addto@macro you'll see that this macro is defined with \xdef (global expanded definition). –  egreg Jun 7 '11 at 15:18
Thank you for the explanation. I tried to write  \\ , but it was misformatted. –  ipavlic Jun 7 '11 at 15:49
@ipavlic Such a command should not be expanded: add \noexpand in front of it. This neutralizes the expandability during an \edef or \xdef. –  egreg Jun 7 '11 at 15:51