[Previous] Lesson 3 [Next]

Saving Stuff for Later

The Auxiliary Stack

Having only one stack is very restrictive, as you can only get at what's on top.  This is no use if you need to get at something, but you're not quite ready to throw out what's stuck on top of it.

Fortunately, TLWNN doesn't have just one stack.  It has an auxiliary stack, onto which you can move things from the main stack in order to access others.

The instructions > and < move an object from the main stack to the auxiliary stack and back respectively.

Thus the "Lord, have mercy" example of the last page can also be written:

Example seven
More compositional text output
[76!111!114!100!]*!
[44!32!104!97!118!101!32!109!101!114!99!121!10!]*!
67!104!114!105!115!116!*!
>!<!

To print the final line, the program moves the procedure that prints ", have mercy" (followed by a newline) into the auxiliary stack in order to print "Lord" first.

Packing a Stack

This is useful for when you want to group things into manageable chunks rather than keep lots of little bits around, or when you want consolidate an unknown number of objects into something you can move about in one piece.  The & instruction is used to pack the auxiliary stack.  The stack then becomes a single object on the main stack.  You can unpack it again by using the ! instruction.  This empties the packed stack onto the auxiliary stack by popping and pushing – therefore, the objects will end up in reverse order to that in which they were before the stack was packed.

For example, take this code:

3>1>4>1>5>9>2>6>5>3>5>8>9>7>9>3>&
2>7>1>8>2>8>1>8>2>8>4>5>9>0>4>5

After this has executed, the main stack will look like this (using {...} to represent a packed stack, beginning at the top):

5
{3, 9, 7, 9, 8, 5, 3, 5, 6, 2, 9, 5, 1, 4, 1, 3}

and the auxiliary stack like this:

4
0
9
5
4
8
2
8
1
8
2
8
1
7
2

If the following code is then executed:

>&>!

then the main stack will be empty (well, apart from something that I haven't told you about yet anyway), and the auxiliary stack will contain the following:

3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
{4, 0, 9, 5, 4, 8, 2, 8, 1, 8, 2, 8, 1, 7, 2}