[Tex/LaTex] Variable-name \newcommand with parameters within another \newcommand

macrosparameters

In "Defining a newcommand, with variable name, inside another newcommand" we learned how to use \newcommand within a command definition with another \newcommand, when the name of the inner command needs to contain a parameter of the outer command. Now, suppose I want to do the same, but for the inner \newcommand to also have parameters, i.e. I want the following code to work:

\newcommand{\defsilly}[1]{%
  % define a command named silly#1 , taking a single parameter
}
\defsilly{willy}
\sillywilly{theparameter}

Motivation: I'm writing a thesis document class, which has a bunch of the following kind of command pairs:

\newcommand{\iitthesis@authorEnglish}{Name of Author}
\newcommand{\authorEnglish}[1]{\renewcommand{\iitthesis@authorEnglish}{#1}}

I want to replace each of these pairs with something like:

\iitthesis@thesisdatafield{authorEnglish}{Name of Author}

This defines both the above commands.

Best Answer

\newcommand{\iitthesis@thesisdatafield}[2]{%
  \@namedef{iitthesis@#1}{#2}}

With

\iitthesis@thesisdatafield{authorEnglish}{Name of Author}

you'd define \iitthesis@authorEnglish to expand to "Name of Author", that is, you'd have issued the equivalent of

\def\iitthesis@authorEnglish{Name of Author}

This wouldn't check for the defined command to be previously undefined. If you want also this check, do

\newcommand{\iitthesis@thesisdatafield}[2]{%
  \expandafter\@ifdefinable\csname iitthesis@#1\endcsname
    {\@namedef{iitthesis@#1}{#2}}}

but for internal commands this isn't usually done.

In your motivation I don't see any need of defining the new command with an argument. If you need also to define a user level command, you can do with the same technique:

\newcommand{\iitthesis@thesisdatafield}[1]{%
  \long\@namedef{#1}##1{\@namedef{iitthesis@#1}{##1}}}

In this case saying

\iitthesis@thesisdatafield{authorEnglish}

would define the command \authorEnglish so that if the user types

\authorEnglish{A. U. Thor}

the effect would be as if doing

\def\iitthesis@authorEnglish{A. U. Thor}

The \long prefix to \@namedef causes \long\def to be executed, so the argument can span one or more paragraphs.

This technique is employed by the LaTeX kernel, where \author{A. U. Thor} actually defines \@author expanding eventually to "A. U. Thor".