6

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?

1

1 Answer 1

6

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

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.