Error with \edef and inner \def,

the \def operation is not expandable. In an \edef \def is simply a non-expandable token that stays unchanged. Similarly \mymacro ends up being defined by \protected\def so does not expand in an \edef.

\show\mymacro

shows

> \mymacro=\protected macro:
#1->\def \do ##1{##1}#1.
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand{\mymacro}{m}{%
    \def\do##1{##1}%
    #1%
}

\begin{document}
    \edef\savedValue{\mymacro{argument}}%
    savedValue: \savedValue
\end{document}

So there are no expandable tokens in the definition of \savedValue so the \edef is equivalent to \def in this case. \show\savedValue shows

   > \savedValue=macro:
->\mymacro {argument}.

Then when \savedValue is expanded it is equivalent to

\def\do#1{#1}argument

If you use \def rather than \protected\def then when you get to the \edef mymacro expands (but \def doesn't so it is the same as

\edef\savedValue{\mymacro{argument}}%

is

\edef\savedValue{\def\do##1{##1}argument}%

then it tries to expand \def but that is not expandable so it is left, then it tries to expand \do so you get the expansion of whatever random definition \do has at this point which happens to be

 \do=\noexpand.

and things go wrong....

Tags:

Macros