2

I want a macro that takes an optional argument.

  • If nothing is passed, it produces G.
  • If i is passed, it produces G_{p_i}.

The following code however is facing some error "Can't use '\spacefactor' in math mode".

\documentclass{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amsthm}
\newcommand{\cabGo}[1][\@empty]{
    \ifx\@empty#1{{\sf G}}
    \else{{\sf G}_{p_{#1}}}
    \fi
}
\begin{document}
$\cabGo$
$\cabGo[3]$
\end{document}
mxant
  • 193

1 Answers1

7

The main problem is missing \makeatletter.

On the other hand, the code is not really well written:

\newcommand{\cabGo}[1][]{%
  \mathsf{G}%
  \if\relax\detokenize{#1}\relax
  \else
    _{p_{#1}}%
  \fi
}

The test for emptiness of the argument is more robust; also \sf has been deprecated for more than 20 years.

If you load xparse, the code is even simpler:

\usepackage{xparse}

\NewDocumentCommand{\cabGo}{o}{%
  \mathsf{G}\IfValueT{#1}{_{p_{#1}}}%
}

The change requested in comments (any number of options can be given)

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\cabGo}{o}
 {
  \mathsf{G}
  \IfValueT{#1}
   {
    \sb{\clist_map_inline:nn { #1 } { p\sb{##1} }}
   }
 }

\ExplSyntaxOff

\begin{document}

$\cabGo$ (no option)

$\cabGo[1]$ (single option)

$\cabGo[1,2]$ (double option)

$\cabGo[1,2,3]$ (triple option)

\end{document}

enter image description here

egreg
  • 1,121,712