5

In the process of a project, I realized it would be helpful if I could do as follows. Say I have a list of different commands (simplified):

\newcommand{\AA}{...}
\newcommand{\AB}{...}
\newcommand{\AC}{...}
...
\newcommand{\AZ}{...}

Now I want a command that can call one of these commands (based on input):

\newcommand{\caller}[1]{\A#1}

The example above won't work, but how would I go accomplishing something that has such a functionality?

5

You have to construct the macro name with \csname A#1\endcsname.

In fact, a lot of package or class code makes use of this \csname ...\endcsname construction and it's not restricted to LaTeX, since both macros are TeX primitives actually.

Please note: \AA is already defined, providing a Scandinavian character, i.e.s something like Å (But since the command names seemed to be simplified, this won't be an issue, I think)

If \A#1 is not defined \csname A#1\endcsname expands to \relax, i.e. it does nothing.

\documentclass{article}



\newcommand{\AB}{bar}
\newcommand{\AC}{foobar}

\newcommand{\caller}[1]{%
  \csname A#1\endcsname%
}


\begin{document}
\caller{A}

\caller{B}

\caller{C}

\caller{Z}
\end{document}

As you can see \caller{A} works (since \AA is defined) and \caller{Z} does nothing (since \AZ isn't defined)

enter image description here

  • 1
    You beat me to the answer by a few seconds. :-) – Mico Feb 4 '16 at 22:04
  • 2
    @Mico: I am becoming an answering machine ;-) – user31729 Feb 4 '16 at 22:09
  • 2
    @ChristianHupfer ... please leave a message at the tone? :) – Sean Allred Feb 4 '16 at 22:23
  • @SeanAllred: lol, sure – user31729 Feb 4 '16 at 22:24

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.