4

I have the following sample code:

\documentclass{article}

\usepackage{etoolbox}

\newcommand{\defineSpecies}[2]{\csdef{spec@#1}{#2}}
\newrobustcmd{\spec}[1]{\csuse{spec@#1}}

\defineSpecies{h2o}{H$_2$O}

\begin{document}

\spec{h2o}
\spec{undefined}

\end{document}

My intention is to redefine \spec{} such that it prints an error message when it provides an empty output, for example for \spec{undefined} which is in fact undefined. Could you please help me how to achieve this goal?

2
  • First of look at chchem or chemmacros for H2O. Secondly, it is not clear what you mean by {} vs {undefined}, there are a lot of tools for you in etoolbox, fx csdefvoid and isblank
    – daleif
    Jun 2, 2021 at 19:28
  • What about catching up "malicious" input like \spec{h2o\endcsname\csname TeX} ? :-) Jun 3, 2021 at 20:39

1 Answer 1

6

You can test whether \spec@#1 exists using \ifcsname <csname>\endcsname, and conditionally print a \GenericError:

\documentclass{article}

\usepackage{etoolbox}

\newcommand{\defineSpecies}[2]{\csdef{spec@#1}{#2}}
\newrobustcmd{\spec}[1]{%
  \ifcsname spec@#1\endcsname% Specification exists
    \csuse{spec@#1}%
  \else% Specification does not exist
    \GenericError{}{Specification `#1' undefined}{}{}%
  \fi}

\defineSpecies{h2o}{H$_2$O}

\begin{document}

\spec{h2o}
\spec{undefined}% This will cause an error.

\end{document}
1
  • Excellent answer, thank you! This is exactly what I looked for.
    – TobiR
    Jun 2, 2021 at 19:31

You must log in to answer this question.

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