0

In my latex document I have defined an array of element and I am making a loop within this array. I would like to define newcommand inside this loop. The idea is to make

\newcommand{\name1}{
  \begin{center}
     \scshape{name1}
   \end{center}
}


\newcommand{\name2}{
  \begin{center}
     \scshape{name2}
   \end{center}
}


\newcommand{\name3}{
  \begin{center}
     \scshape{name3}
   \end{center}
}

What I did is:

\usepackage{pgffor}
\def \peopleArray {name1, name2, name3}
\foreach \x in \peopleArray {
  \newcommand{\x}{
     \begin{center}
        \scshape{name3}
      \end{center}
  }
}

but this won't work.

I have also tried this

\foreach \x in \peopleArray {%
    \expandafter\xdef\csname \x\endcsname{\begin{center}
            \scshape{x}
    \end{center}}
}

but this doesn't work either

4
  • 1
    It would be nice if you could give a simple compilable example... notice however that numbers can't be part of a LaTeX macro name (although you can do tricks, see for example package etoolbox, maybe \csuse and company can help you), and then, \scshape is a switch, so you should use {\scshape wwhatever}.
    – Rmano
    Jul 26 at 16:37
  • 1
    In addition to what @Rmano says, each cycle in a \foreach loop is executed in a group, so the \newcommand will be lost.
    – egreg
    Jul 26 at 16:47
  • @Rmano well, the code won't have any number in it. I just used them for the sake of the example. What I don't understand in your comment is: so it is not possible? Jul 26 at 16:51
  • 2
    @FabienneLablatte Perhaps it's better that you make a more “real world” example, then.
    – egreg
    Jul 26 at 16:52
1

Here's one way to define a sequence of macros with a for loop, with an example of usage:

\documentclass{article}
\usepackage{pgffor}
\def \peopleArray {\nameA, \nameB, \nameC}
\begin{document}
\foreach \x in \peopleArray {
  \expandafter\newcommand\x{}% error if already defined
  \expandafter\gdef\x{
     \begin{center}
        {\scshape name3}
      \end{center}
  }
}
\nameA
\nameB
\nameC
\end{document}

I had to use \gdef instead of \newcommand because otherwise the definition is local (and lost) instead of global.

I'm not sure this is useful though, because name3 is the same in all cases.

3
  • you should add \newcommand so that you get a error if you overwrite an existing command. Jul 26 at 18:19
  • @UlrikeFischer How would you make the \newcommand global?
    – edemaine
    Jul 26 at 18:29
  • 1
    you don't have to, you can use \newcommand to test and then \gdef Jul 26 at 18:32

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.