Is it possible to test whether a token register is empty without expanding it?
How to Test if Token Register is Empty
conditionalstex-coretoken-lists
conditionalstex-coretoken-lists
Is it possible to test whether a token register is empty without expanding it?
Best Answer
At time of writing the other TeX based answers on this page are flawed in that they hide a conditional
\ifx
inside a macro but still use\else
/\fi
at the "top" level. This will mean that things break unexpectedly when used inside other conditionals.The LaTeX3 programming language expl3 contains a module for doing stuff with token registers:
It essentially does internally what the other answers here are suggesting, but it uses expansion to grab its arguments so the branching is robust (and you don't have
\fi
lying around to get in your way).Update: So what does this approach do that is superior to other methods? Consider the style of solution first offered in answer to this question:
This doesn't behave nicely when nested, because TeX scans ahead when discarding unfollowed branches of a conditional. Consider
If
\bar
=\baz
, then the second branch is discarded and the first branch is executed. So far so good. If\bar
≠\baz
, then the first branch is discarded by reading ahead until the first unmatched\else
— and this is the one in the line labelled "uh oh" above. So you could collapse the expansion of the above snippet in this case to:and hence the cause of the ‘Extra
\else
’ error message in this case.So this form for conditionals doesn't work so well. Next try. You can also write this style of code like this:
This avoids the problems of nesting as in the previous trial solution, but it's prone to another problem:
#2
and#3
have trailing material behind them, namely\else
and\fi
. This is a problem if you want to write something likebecause the
#1
passed to\processfoo
will be\fi
instead of the desired{arg}
. The conditional in this case is better written asso overcome this problem. This is how expl3 conditionals work, and it's why we're writing
TF
at the end of all their names to indicate "true" and "false" branches. (Or justT
or justF
if you only want one of them.)Incidentally, there are expandable tests for checking for emptiness, which is why I suggest using the expl3 approach for this test. Expandability is not always required, of course, but code that is fully expandable tends to be more reliable and it's always nice to have for cases such as