3

Given the following sample code:

\documentclass{article}

\newtoks\foo
\foo={foo}

\begin{document}
\the\foo,
\begingroup
\foo={bar}
\the\foo
\the\global\foo  % <-- fails
\endgroup
\end{document}

This fails with

! You can't use `\global' after \the.

My question simply is, is it possible to get the global value of \foo from within a local group? As I guess it's not, what are the suggested alternatives (especially with regard to speed and cleaning up scratch memory after parsing is done)?

Some background information: What I'm trying to do is to write a more complex parser in LaTeX where I use a global token register to store the rest of the input string. For building the final result, I need to maintain a list of sub-expressions for which I wrap my whole parser into a local group to have a list of scratch token registers. The number of used registers grows and shrinks while parsing.

With big inputs it may now happen that the number of used local registers clashes with the number of the global token register used for the input. So the idea was to somehow make sure that whenever I need to access the input string, only the global register is read/written.

  • 1
    you should only ever use a register for global access or local access otherwise you are likely to fill TeX's save stack, that is why the unallocated scratch registers 0-9 have the convention specified in the TeXBook that odd numbers are used for global and even for local use. There is no way to access the global value (it is stored on the save stack internally) – David Carlisle Sep 24 '18 at 7:47
  • with no example it is hard to guess your use case, but if you need to be able to have local nested instances of your parser you should write it only using local assignments. or if you really need global assignments you need to maintain your own stack of vales and save and restore them (the blkarray package has some comments about that) – David Carlisle Sep 24 '18 at 7:50
  • Your concept of local/global doesn't make really sense when retrieving values. If you add more nesting groups you get a stack of values, foo1, foo2, foo3, foo4. Which one is the global one when you are in group 4? foo3 or foo1? – Ulrike Fischer Sep 24 '18 at 7:56
  • @DavidCarlisle There is no nested grouping involved here, I just open a single local group to get a clean stack of registers, and close it when I'm done. The global register is necessary with this approach as I have to get the final result out of the local group eventually – siracusa Sep 24 '18 at 7:57
  • 2
    you do not need a global register for that \expandafter\endgroup\the\foo will escape a token register out of one level of grouping or if you want to re-assign it \expandafter\endgroup\expandafter\foo\expandafter{\the\foo} – David Carlisle Sep 24 '18 at 7:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.