Create a stack of items
A would expect a stack to build up from the front not the end, so here I reverse the stack for \print
This assumes the tokens in the items are safe in an \edef
\catcode`\!=4
\def\createlist#1{\def#1{}}
\def\push#1#2{\edef#1{#2!#1}}
\def\pop#1{\edef#1{\expandafter\xpop#1}}
\def\xpop#1!{}
\def\print#1{\expandafter\xprint#1!\xpop!\relax}
\def\xprint#1!#2\relax{\ifx\xpop#1\else\xprint#2\relax#1\fi}
\catcode`\!=12
\createlist{\mylist}
\push{\mylist}{A}
\push{\mylist}{-B}
\push{\mylist}{-C}
\print{\mylist} % prints A-B-C
\pop{\mylist} % Removes `-C'
\print{\mylist} % prints A-B
\bye
Just for completeness, if you're using a TeX engine with ε-TeX (that is, not Knuth TeX), then you can use seq
variables from expl3
, which have most of the stack functionality you want:
\input expl3-generic
\ExplSyntaxOn
\tl_new:N \lastpop
\cs_new_eq:NN \createlist \seq_new:N
\cs_new_eq:NN \push \seq_push:Nn
\cs_new_protected:Npn \pop #1
{ \seq_pop:NN #1 \lastpop }
\cs_new_protected:Npn \print #1
{
\tl_clear:N \lastpop
\seq_map_inline:Nn #1
{ \tl_put_left:Nn \lastpop {##1} }
\tl_use:N \lastpop
}
\ExplSyntaxOff
\createlist{\mylist}
\push{\mylist}{A}
\push{\mylist}{-B}
\push{\mylist}{-C}
\print{\mylist} % prints A-B-C
\pop{\mylist} % Removes `-C' (`-C' is available in \lastpop)
\print{\mylist} % prints A-B
\bye