8

How can I include symbols defined as macros in an array and then access them with \pgfmathparse? The following dies with a

"missing control sequence:

\inaccessible" error

\documentclass{article}
\usepackage{tikz}
\usepackage{wasysym}
\begin{document}

\def\planets{{"\mercury","\venus","\mars","\jupiter","\saturn","\uranus","\neptune"}}

\foreach \i in {0,...,6}{
\pgfmathparse{\planets[\i]}\pgfmathresult - 
}
\end{document}
6

Don't iterate over control sequences. Instead build them from their names using \csname ... \endcsname:

\documentclass{article}
\usepackage{tikz}
\usepackage{wasysym}
\newcommand\planets{{"mercury","venus","mars","jupiter","saturn","uranus","neptune"}}
\begin{document}
% without using an array and pgfmathparse
\foreach \i in {mercury, venus,mars,jupiter,saturn,uranus,neptune}{
\csname\i\endcsname}

% using the array
\foreach \i in {0,...,6}{
\pgfmathparse{\planets[\i]}\csname\pgfmathresult\endcsname}

\end{document}

output of code

2

The planet symbol commands don't survive \edef, which is performed when \planets[\i] is evaluated.

You can avoid the problem by defining \planets with \noexpand in front of each item:

\documentclass{article}
\usepackage{pgffor}
\usepackage{wasysym}

\newcommand\planets{{%
  "\noexpand\mercury",%
  "\noexpand\venus",%
  "\noexpand\mars",%
  "\noexpand\jupiter",%
  "\noexpand\saturn",%
  "\noexpand\uranus",%
  "\noexpand\neptune"%
}}

\begin{document}

\foreach \i in {0,...,6}{\pgfmathparse{\planets[\i]}\pgfmathresult{} - }

\end{document}

enter image description here

However, if your aim is to be able to refer to a planet by its number, I suggest a different approach. The indexing starts at 1.

\documentclass{article}
\usepackage{xparse}
\usepackage{pgffor}
\usepackage{wasysym}

\ExplSyntaxOn
\NewExpandableDocumentCommand{\planet}{m}
 {
  \tl_item:nn { \mercury\venus\mars\jupiter\saturn\uranus\neptune } { #1 }
 }
\ExplSyntaxOff

\begin{document}

\foreach \i in {1,...,7}{\planet{\i} - }

\planet{3}

\end{document}

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.