I'm having difficulty understanding (and appreciating) the concept of expandability. I'm very murky about understanding when and how expandability impacts me in writing code for my documents.
I've read Why isn't everything expandable?. The answer was interesting and useful, but it didn't get at the heart of what I'm curious about. I've also perused a number of the answers to other questions involving expandability: of particular interest was this post.
In respondence to a recent question of mine, it was explained that document commands are protected and hence not expandable. Understanding this allowed me to write what I wanted and to get the effect I expected.
And in a comment to another question of mine, it was explained how one should use \cs_new_protected:Npn
"when the function does unexpandable jobs such as setting token lists or sequences."
For years, I've been writing code like
\newcommand{\currentanswer}{}
\newcommand{\setcurrentanswer}[1]{\renewcommand{\currentanswer}{#1}}
knowing that after calling \setcurrentanswer
, any call to \currentanswer
will result in the desired output. Am I relying upon (un)expandability here? I'm not really sure; I only know that it does what I want. Then there are times I know I can throw in a \protect
to get the result I want: but, I really don't understand the why of it; I just know it gets the job done.
Recently, I've been trying to learn some LaTeX3: the more I play with it, the more I like it. LaTeX---which I always thought was pretty powerful---is suddenly much more powerful and transparent in the manner that macros and functions can be defined. But now, I also seem to be running up against this issue of expandability, whereas before I could blithely go about my business ignorant of some of the subtlies of what I was doing.
While I am asking multiple questions here, I suspect that they really have much the same answer: hence I'm not splitting them across multiple posts.
Could someone take the time to explain some of the nuances of expandability, or, if not, point me to a good reference?
How do I know when I'm working with a protected function/macro?
Is protected and unexpandable the same thing?
Could someone explain the preference for protected functions in LaTeX3?
And finally, apart from the answers to the above questions, why would it be preferrable to protect functions which perform unexpandable tasks: such as setting tokens and sequences? (I am very interested in understanding this last question.)