3

Is it possible to have a command alternate its behaviour?

My idea is something like this:

\documentclass{article}

\def \current {c}

\def \abc {
    \ifx\current{a}
        \def\current{b}
    \else
        \ifx\current{b}
           \def\current{c}
        \else
           \def\current{a}
        \fi
    \fi     
    \current       
}

\begin{document}
    \abc \abc \abc
\end{document}

I'd expect this to output a b c, but instead I get:

enter image description here

I'm guessing that the logic inside is only run when the \abc is being defined, and that's why it's always stuck at a. How can I write something with the desired behaviour?

  • 1
    no the expression inside a command definition is not evaluated at all (the replacement text can use undefined commands and there is no error if the command is not used) – David Carlisle Feb 11 at 23:18
  • 1
    You've fallen in the XY problem fallacy :-) It's usually best not to edit a question in a way that invalidates existing answers. In such cases it's best to ask a new question altogether – Phelype Oleinik Feb 11 at 23:34
  • @PhelypeOleinik Will do so :) – Luke Collins Feb 11 at 23:35
  • @PhelypeOleinik actually it was only a minor tweak here I edited the answer to match – David Carlisle Feb 11 at 23:38
  • @LukeCollins Thanks! Though David was faster :-) Seems like I caused a big mess with one single comment... – Phelype Oleinik Feb 11 at 23:43
6
 \ifx\current{

compares \current against { which is not what you intended,

\documentclass{article}


\def\currenta{a\let\abc\currentb}
\def\currentb{b\let\abc\currentc}
\def\currentc{c\let\abc\currenta}
\let\abc\currenta


\begin{document}
    \abc \abc \abc
\end{document}

For the updated case note that the argument of \color has to expand to a name, so can not have assignments, and the tikz for loop groups each iteration so you need a global assignmet

\documentclass{article}
\usepackage{tikz}

\definecolor{myBlue}{RGB}{0,114,206}
\definecolor{myYellow}{RGB}{255,199,44}
\definecolor{myBrown}{RGB}{154,51,36}

\def\currentblue{\color{myBlue}\global\let\currentcol\currentyellow}
\def\currentyellow{\color{myYellow}\global\let\currentcol\currentbrown}
\def\currentbrown{\color{myBrown}\global\let\currentcol\currentblue}
\global\let\currentcol\currentblue

\begin{document}
    \tikz{
        \foreach \i in {1,...,10} {
            \node at (\i,\i) {\currentcol \i};
        }}
\end{document}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.