# Use of a macro to set counter value in another macro

I am trying to simply set the value of the counter try which I defined previously to the value of the output of the \foo command. However this does not work. I guess that the problem is coming from the fact that in the \test macro the \foo one is not expanded at the right time of compilation. Since I know really few concerning macros and their expansion I am not able to find the solution here.

\documentclass{book}

\usepackage{ifthen}

\newcounter{try}

\newcommand{\foo}[1]{\ifthenelse{#1=1}{1}{0}}

\newcommand\test[1]{\setcounter{try}{\foo{#1}}%
\arabic{try}}

\begin{document}

Result of foo\{3\}: \foo{3}
Result of test\{3\}: \test{3}

\end{document}

-

The second argument to \setcounter is expanded by TeX that wants to see a <number> there. So you need an expandable test, which \ifthenelse isn't: rather than expanding to a number, it expands to the instructions for producing a number.

The easiest way is to use the primitive conditional \ifnum:

\documentclass{book}

\newcounter{try}

\newcommand{\foo}[1]{\ifnum#1=1 1\else0\fi}

\newcommand\test[1]{\setcounter{try}{\foo{#1}}%
\arabic{try}}

\begin{document}

Result of \verb|\foo{3}|: \foo{3}
Result of \verb|test{3}|: \test{3}

Result of \verb|\foo{1}|: \foo{1}
Result of \verb|test{1}|: \test{1}

\end{document}


Note the space after =1 that is necessary in all cases a “naked” constant appears (the space gets ignored by TeX).

Alternatively, use etoolbox:

\documentclass{book}
\usepackage{etoolbox}

\newcounter{try}

\newcommand{\foo}[1]{\ifnumcomp{#1}{=}{1}{1}{0}}

\newcommand\test[1]{\setcounter{try}{\foo{#1}}%
\arabic{try}}

\begin{document}

Result of \verb|\foo{3}|: \foo{3}
Result of \verb|test{3}|: \test{3}

Result of \verb|\foo{1}|: \foo{1}
Result of \verb|test{1}|: \test{1}

\end{document}


Here's the output for both cases

-
Thanks for your answer which is working fine. This question led me to another one: What should I do if \foo is defined as \newcommand{\foo}[1]{\StrBefore{#1}{.}} using the xstring package? –  Ludovic C. Sep 15 '13 at 11:13
@LudovicC. This has the same problem: \StrBefore doesn't expandably produce its result. Maybe you want to make another question better specifying your context and the expected values to argument #1. –  egreg Sep 15 '13 at 11:16

I don't know where the problem comes from exactly, but you'd be better off using etoolbox rather than ifthen; see Why is the ifthen package obsolete?.

\documentclass{book}

\usepackage{etoolbox}

\newcounter{try}

\newcommand{\foo}[1]{\ifnumequal{#1}{1}{1}{0}}

\newcommand\test[1]{\setcounter{try}{\foo{#1}}%
\arabic{try}}

\begin{document}

\noindent
Result of foo\{3\}: \foo{3}\\
Result of test\{3\}: \test{3}\\
Result of foo\{1\}: \foo{1}\\
Result of test\{1\}: \test{1}

\end{document}


-