Thats a problem I encountered several times during the last weeks. I try to use macros as arguments of other macros, and it doesn't work.
The most recent example: I try to use \addcontentsline to put a name from a datatool database into the table of contents.
MWE 1:
\documentclass{article}
\usepackage{datatool}
\DTLnewdb{database}
\DTLnewrow{database}
\DTLnewdbentry{database}{shortcut}{JD}
\DTLnewdbentry{database}{name}{John Doe}
\begin{document}
\tableofcontents
%this works and produces the output "John Doe"
\DTLfetch{database}{shortcut}{JD}{name}
%if I use the same command inside \addcontentsline,
%it doesn't work and returns errors
\addcontentsline{toc}{section}{\DTLfetch{database}{shortcut}{JD}{name}}
\end{document}
I'm not (only) asking for a solution to this particular problem, but for a more general explanation what I should consider when using macros as arguments of other macros and what can cause errors when doing so.
I'm sorry if that's a stupid question, but I wasn't able to find any information about that topic, neither in The LaTeX Companion nor the internet, although I spent many hours searching.
EDIT: Please provide a general answer instead of only solving the problems in the MWEs, if possible. I'd like to understand a bit of what causes those errors and how to avoid them, and I imagine there are many unexperienced users out there who might also find this useful.
To illustrate what kind of problems I'm talking about, here is another MWE with a problem similar to MWE 1. I tried to solve it by adding \protect randomly on several places (as egreg did in his answer with MWE 1, except I guess HE knew what he was doing ;-) ), but I couldn't make it work in this way.
MWE 2:
\documentclass{article}
\usepackage{datatool}
\DTLnewdb{database}
\DTLnewrow{database}
\DTLnewdbentry{database}{shortcut}{JD}
\DTLnewdbentry{database}{name}{John Doe}
%command which reads and prints the name belonging to the shortcut
\newcommand{\readname}[1]{\DTLfetch{database}{shortcut}{#1}{name}}
%environment for some text written by the author whose shortcut is in the argument
\newenvironment{authorstext}[1]{%
\addcontentsline{toc}{subsection}{#1}%when this line is removed, everything works
{\textbf{#1} has written this text:}%
}{}
\begin{document}
\tableofcontents
\section{Authors}
%this doesn't work
\begin{authorstext}{\readname{JD}}
Some text by John Doe.
\end{authorstext}
%this works
\readname{JD}
\end{document}
\DTLassignfirstmatch) rather than writing\DTLfetchin the toc, as the approach in your MWE results in twice the number of database lookups than is otherwise necessary. For a small number of uses, this isn't too much of a problem, but for large scale use this may significantly slow the document build. – Nicola Talbot Jun 22 '14 at 18:29