Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

When I compile this minimum LaTeX file:

\documentclass{report}

\def\defMacro#1#2{\expandafter\def\csname#1\endcsname{#2}}
\def\useMacro#1{\csname#1\endcsname}

\usepackage{pgffor}

\begin{document}
\foreach \n in {0,1,...,10}{
\defMacro{number:\n}{\n}
}


\useMacro{number:8}
\end{document}

I obtain no PDF output. What do I mistake?

share|improve this question
1  
The etoolbox package provides \csdef and \csuse which do the same as \defMacro and \useMacro. LaTeX itself defines \@namedef and \@nameuse. The \csuse macro takes care not to define the given macro (equal to \relax) if it doesn't exists. It expands to nothing in this case. –  Martin Scharrer Apr 20 '11 at 15:23
add comment

1 Answer

up vote 3 down vote accepted

The \foreach loop content is executed in a group for each iteration, therefore the definition is only local. You would need to add \global in front of \defMacro.

The reason the \useMacro is not causing an error is because \csname has the side effect that the resulting macro is defined equal to \relax if is was undefined before.

share|improve this answer
    
I changed the second line in \def\defMacro#1#2{\expandafter\gdef\csname#1\endcsname{#2}}. Thanks –  Azoun Apr 20 '11 at 15:33
    
@Azoun: Note that this of course makes all \defMacro definitions global, which might be an issue dependent on the use. For your own private macros this shouldn't be an issue, but I wouldn't do that for package code. –  Martin Scharrer Apr 20 '11 at 15:36
    
I'm just beginning to learn TeX...so I'm just playing. Many thanks for the advice –  Azoun Apr 20 '11 at 15:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.