Use a conditional
\documentclass{article}
\newif\ifoff
\newcommand{\onoff}{%
\relax\ifoff off\global\offfalse\else on\global\offtrue\fi
}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
or a counter
\documentclass{article}
\newcount\offcount
\newcommand{\onoff}{%
\relax
\ifodd\offcount
\global\advance\offcount 1
off%
\else
\global\advance\offcount -1
on%
\fi
}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
In both cases, if you want only local redefinitions, remove \global
.
Note the starting \relax
, necessary if you want to use \onoff
in tables.
An abstract version, with the help of etoolbox
that makes things a bit easier with toggles (it could be realized with conditionals).
\documentclass{article}
\usepackage{etoolbox}
\newcommand{\newalternatingcommand}[3]{%
\newcommand{#1}{%
\iftoggle{\string#1}
{#2\global\togglefalse{\string#1}}
{#3\global\toggletrue{\string#1}}%
}%
\newtoggle{\string#1}%
\toggletrue{\string#1}%
}
\newalternatingcommand{\onoff}{on}{off}
\begin{document}
\onoff
\onoff
\onoff
\end{document}
\def\onoff{\a\let\c\a\let\a\b\let\b\c}
in your set-up works.\edef
would do as well.\def\c{\a}
says "define\c
to expand to\a
" (thus eventually to the future contents of\a
), not "… to the (current) contents of\a
".\let
essentially says the latter.\edef
expands macros at definition time rather than use time, which is why it would also work here.