[Tex/LaTex] On/Off switch (redefine a macro at each use)

funmacros

I try do define a macro \onoff, which alternatively prints "on" and "off" each time it's used. For example the sequence \onoff \onoff \onoff would print on off on

My first guess would be to use the following code:

\def\a{on}
\def\b{off}    
\newcommand\onoff{\a\def\c{\a}\def\a{\b}\def\b{\c}}

However this code doesn't work. Is there an elegant way to code this?

Best Answer

One way

\documentclass{article}

\makeatletter
\def\@ONoff {on\let\onoff\@onOFF}
\def\@onOFF {off\let\onoff\@ONoff}
\let\onoff\@ONoff
\makeatother

\begin{document}

\onoff\onoff\onoff\onoff\onoff\onoff...

\end{document}

onoffonoffon

Another way (was a now deleted separate answer)

\documentclass{article}

\makeatletter
\def\onoff{\@onoff{on}{off}}
\def\@onoff #1#2{#1\def\onoff {\@onoff{#2}{#1}}}
\makeatother

\begin{document}\thispagestyle{empty}

\onoff\onoff\onoff\onoff\onoff\onoff...

\end{document}

onoffonoffon

A third way

\documentclass{article}

\makeatletter
\def\onoff {\onoroff{on\let\onoroff\@secondoftwo}{off\let\onoroff\@firstoftwo}}
\let\onoroff\@firstoftwo
\makeatother

\begin{document}

\onoff\onoff\onoff\onoff\onoff\onoff\onoff...

\onoff\onoff\onoff\onoff\onoff...

\end{document}

more on off

Related Question