3

Goal :

I would like to create a variable that could be dynamically updated.

Context :

Every chapter of my document has a specific keyword (actually a bibtex entry). And sometimes, I need to print it, or use it as a parameter for another command. So I need to define a first command that stores the keyword, and another command that prints it. Thereby, for every new chapter, the keyword changes, and so does the variable.

So far :

This is the commands I (think I) would need :

\newcommand{\aNewChapter}[2]{%
  \textbf{#1} % The title of the chapter
  \setVariable{#2} % The definition of the variable
}
\newcommand{\setVariable}[1]{#1} 
\newcommand{\printVariable}{???}
\begin{document}
\aNewChapter{The first chapter}{keyword1}
Some text...
\printVariable % this should, in this case, print 'keyword1'
The rest of the text
\end{document}

The idea doesn't seem massively complex, but I can't find any solution to achieve it. It would be easy if I set the variable manually, rather than with a parameter. But I need this 'dynamic' way of doing. The problem is then that I don't know how to print it.

It seems so easy that I almost feel dumb to ask that...

  • 2
    I think \newcommand is already what you're looking for :-) If you define a "Variable" with \newcommand{\myvariable}, set and update it with \renewcommand{\myvariable}, you can print it by just saying \myvariable. – Stephan Lehmke Jun 25 '14 at 14:44
  • I don't think it works, I need to set the variable with an argument. I updated my post with more content to show how it should work... – BonyHoax Jun 25 '14 at 14:55
  • Have you tried replacing \setVariable{#2} with \renewcommand{\myVariable}{#2} and \printVariable with \myVariable? – Stephan Lehmke Jun 25 '14 at 14:58
  • Yes. It only prints the title of the chapter. Not the keyword. – BonyHoax Jun 25 '14 at 15:06
5

Here's a complete example based on my comments:

\documentclass{article}

\newcommand{\aNewChapter}[2]{%
  \textbf{#1} % The title of the chapter
  \setVariable{#2} % The definition of the variable
}
\newcommand\myVariable{}
\newcommand{\setVariable}[1]{\renewcommand{\myVariable}{#1}} 
\newcommand{\printVariable}{\myVariable}
\begin{document}
\aNewChapter{The first chapter}{keyword1}
Some text...
\printVariable % this should, in this case, print 'keyword1'
The rest of the text
\end{document}

If this is not what you're looking for, you should refine the question.

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.