3

I want renew a variable in a foreach loop, but my codes won't work. Please help!

\documentclass{article}
\usepackage{pgffor}
\newcommand\tests{
  \newcommand\mytext{aaa}
  \foreach \i in {bbb,ccc,ddd,eee,fff}{
    \renewcommand\mytext\i
  }
  \mytext
}
\begin{document}
  \tests
\end{document}\

It output string "aaa", not "fff"!

4

The \foreach loop implicitly sets a group. Therefore, the redefinition is lost in the next loop or after the loop. A global definition helps, e.g.:

\documentclass{article}
\usepackage{pgffor}
\newcommand\tests{
  \newcommand\mytext{aaa}
  \foreach \i in {bbb,ccc,ddd,eee,fff}{
    \global\let\mytext\i
  }
  \mytext
}
\begin{document}
  \tests
\end{document}

Result

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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