I have the following situation: I want to use the argument of \newcommand
to be the name of a new variable, which I define within \newcommand
using \def
.
When I try to compile it always says that my newly defined variable doesn't exist. I think the problem is the "#"-symbol of the argument within the \def
command.
\documentclass{article}
\newcounter{src}
\newcommand{\src}[1]{\stepcounter{src}\def \#1 {\arabic{src}} [\arabic{src}]}
\begin{document}
\src{testone}
\src{testtwo}
first test: \testone
second test: \testtwo
\end{document}
My expected output would be:
1
2
first test: 1
second test: 2
But instead I get:
! Undefined control sequence. \testone
! Undefined control sequence. \testtwo
Does anyone have a solution for how to use the #
for a variable name?
Best Answer
The construction of command sequence names can be done with
\csname #1\endcsname
but this is not sufficient for
\def
, it must be prepended with\expandafter
, to expand the sequence name first, then use\def
(the same holds for\edef
etc.)i.e.:
\expandafter\def\csname #1\endcsname{some expansion stuff}
will expand to
\def\foo{some expansion stuff}
if#1
contains foo.I used
\edef
here to use the counter number at the time of definition of the macro name, otherwise\arabic{src}
would print the current number.