0

Why is this not working and what can I do to get it to work?

\documentclass[tikz,border=5]{standalone}

\newcommand{\lastsave}{defaulttext}
\newcommand{\save}[1]{\def\lastsave{#1}#1}

\begin{document}
\begin{tikzpicture}
\node at (0,0) {\save{text}};
\node at (0,-1) {\lastsave};
\end{tikzpicture}
\end{document}

enter image description here

Afterall, it does work outside of tikz:

\documentclass[tikz,border=5]{standalone}

\newcommand{\lastsave}{defaulttext}
\newcommand{\save}[1]{\def\lastsave{#1}#1}

\begin{document}
\save{text}

\lastsave    
\end{document}

enter image description here

  • 1
    Use \gdef instead \def : \newcommand{\save}[1]{\gdef\lastsave{#1}#1}. So the new definition of \lastsave is valid outside the current group too. – esdd Dec 9 '15 at 11:59
  • @esdd: Also: Could you explain what this group-thing is? Do don't mean an environment or something like that, do you? – Make42 Dec 9 '15 at 12:40
3

Because \node sets the node text inside a group you have to use \gdef instead \def. Then your redefinition is global:

\documentclass[tikz,border=5]{standalone}
\newcommand{\lastsave}{defaulttext}
\newcommand{\save}[1]{\gdef\lastsave{#1}#1}% <- changed
\begin{document}
\save{text}
\lastsave
\end{document}

With \def your redefinition is valid only in the current group. In your second example there in no additional group inside the document. So you get what you want. But if you set \save inside a group, that means {\save{...}} or \begingroup\save{...}\endgroup or \bgroup\save{...}\egroup, then your redefinition is limited by this group.

\documentclass{article}
\newcommand{\lastsave}{defaulttext}
\newcommand{\save}[1]{\def\lastsave{#1}\lastsave}

\begin{document}
\save{first text} stores the text -- \lastsave

\bigskip

But using the command inside a group like

\bigskip
{\save{second text}},
\begingroup \save{third text}\endgroup,
\bgroup\save{fourth text}\egroup,

\begin{center}
  \save{last text}
\end{center}

you still get -- \lastsave{} -- outside the groups.

\end{document}
  • Are environments and commands groups as well? – Make42 Dec 9 '15 at 14:49
  • Yes, environments are groups. If you use something like \textbf{\save{text}} the \save command is also in a group. – esdd Dec 9 '15 at 15:17

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.