Command that changes its definition the nth time it's used
Have a look at the following example:
\documentclass{article}
\newcounter{testcount}
\newcommand{\modifyme}{%
\addtocounter{testcount}{1}
\ifnum\thetestcount<3%
Hello
\fi
\ifnum\thetestcount>2%
World
\fi
}
\newcommand{\resetme}{\setcounter{testcount}{0}}
\begin{document}
\modifyme
\modifyme
\modifyme
\modifyme
\resetme
\modifyme
\end{document}
I love using counters! Here only the expansion after the number specified in \changedefinitionafter
is modified.
\documentclass{article}
\pagestyle{empty}% for cropping
\makeatletter
\newcount\count@foo
\newcount\nth@foo
\newcommand\changedefinitionafter[4]{
% #1: name of macro
% #2: exceptional occurence
% #3: normal expansion
% #4: exceptional expansion
\global\count@foo=0
\global\nth@foo=#2
\gdef#1{%
\advance\count@foo by 1
\ifnum\count@foo=\nth@foo
#4%
\else
#3%
\fi
}
\edef\resetname{reset\expandafter\@gobble\string#1}
\expandafter\gdef\csname \resetname \endcsname{\global\count@foo=0 }
}
\makeatother
\begin{document}
\obeylines
\changedefinitionafter\foo{3}{OneTwoThree}{Next}
\foo
\foo
\foo
\foo
\resetfoo
\foo
\foo
\foo
\foo
\end{document}
No counter, but three macros for each command of this type:
\documentclass{article}
\makeatletter
\newcommand{\newchangingcommand}[4]{%
% #1 = macro name
% #2 = steps
% #3 = value until step #1
% #4 = value from step #1
\@namedef{\string#1@counter}{0}%
\@namedef{\string#1@limit}{#2}%
\def#1{%
% step the counter
\global\@nameedef{\string#1@counter}{\number\numexpr\@nameuse{\string#1@counter}+1\relax}%
\ifnum\@nameuse{\string#1@counter}=\@nameuse{\string#1@limit}\relax
\gdef#1{#4}#4%
\else
#3%
\fi
}%
}
\providecommand\@nameedef[1]{\expandafter\edef\csname#1\endcsname}
\makeatother
\newchangingcommand{\foo}{3}{Two}{Next}
\newchangingcommand{\foob}{2}{One}{Next}
\begin{document}
\foo--\foob\par
\foo--\foob\par
\foo--\foob\par
\foo--\foob\par
\end{document}
Be aware that using such commands in moving arguments will fail for several reasons.