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

Make42
  • 1,772
  • 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 09 '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 09 '15 at 12:40

1 Answers1

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}
esdd
  • 85,675