2

I want to have a command called \ensureinfocommand that can be called like this:

\ensureinfocommand{studentid}

This call will check if the command \studentid already exists and if not, it should create the following:

\newcommand\studentid[1]{
    \newcommand\@studentid{#1}
}

I tried implementing \ensureinfocommand like the following:

\newcommand\ensureinfocommand[1]{
    \ifcsname#1\endcsname\else
        \expandafter\newcommand\csname#1\endcsname[1]{
            \expandafter\newcommand\csname @#1\endcsname{##1}
        }
    \fi
}

This creates all the necessary commands, but the output of \@studentid is wrong.

\ensureinfocommand{studentid}
\studentid{1234567}

\begin{document}
\@studentid
\end{document}

This prints studentid and not 1234567 and I don't get why. Does anybody see what's wrong with my commands?

3
  • don't show only snippets, always make a small but complete example, that makes testing much easier. May 17, 2023 at 11:06
  • 2
    Are you aware of \providecommand? It's like \newcommand, but only executes if the command doesn't already exist. So it would save you from the \ifcsname part.
    – Teepeemm
    May 17, 2023 at 12:49
  • @Teepeemm no, I was not ware of \providecommand. Thanks for pointing me to that.
    – Luke
    May 17, 2023 at 13:18

1 Answer 1

4

You are missing \makeatletter in using \@studentid.

\documentclass{article}
\newcommand\ensureinfocommand[1]{%
    \ifcsname#1\endcsname\else
        \expandafter\newcommand\csname#1\endcsname[1]{%
            \expandafter\newcommand\csname @#1\endcsname{##1}%
        }%
    \fi
}

\ensureinfocommand{studentid}
\studentid{1234567}

\begin{document}
\makeatletter\@studentid\makeatother
\end{document}

I also took the liberty to add suitable %'s to avoid extraneous space tokens.

1
  • Ah, thanks a lot. I had not thought of that at all!
    – Luke
    May 17, 2023 at 11:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .