The Stack

What is the stack? Well, the stack is exactly what it sounds like. It's a stack. Of numbers, that is.

This is what a typical stack might look like while Cave Story is running:
The Stack

It's just a pile of hex numbers that are stacked on top of each other. Notice that the program uses the stack frequently, so there's already some stuff on the stack.

The PUSH instruction will push a number onto the stack. Literally. Like this:
PUSH 6077
This is what happens:
Push number 6077

The number 6077 is pushed onto the stack, which is shown in green in the above diagram. You can also PUSH a register. The instruction PUSH EAX will push the contents of EAX onto the stack.

What if you want to remove some stuff from the top of the stack? You use POP.
This will take the top value of the stack, pop it off, and store it into EAX:
Pop stack and store to EAX

Now EAX holds the number 6077. Pretty easy, right?

You can also push multiple things onto the stack.
PUSH 77491
Push 3 times

Notice that DE0335, the number that was most recently pushed, is on the top of the stack.

Now you can remove each number one by one:
Pop the stack 3 times

The stack is a great way to store numbers so that you don't lose them later. However, the stack is also a lot more powerful than simply a storage system. There are two stack pointers you need to be aware of: ESP and EBP. ESP points to the location of the top of the stack, and EBP is used to manipulate things near the bottom or middle of the stack. Without these registers, the program would never know where the stack is. Here's one example of more complex usage of the stack: framerects for Cave Story sprites are values that'll get MOVed right into the stack without the help of PUSH and POP (this is done by directly using EBP). We'll see an example of this later when we begin messing with framerects.

Oh, by the way, be careful when using PUSH and POP. If you push 5 values onto the stack, but you don't remove them later, that can cause problems. Also, if you didn't PUSH anything yet, don't just do a POP EAX randomly. It might remove an important number that's already on the stack, something that the program needs to run properly. So if you PUSH 3 numbers onto the stack, remember to POP 3 times. If you PUSH 8 numbers onto the stack, POP 8 times somewhere later in the code.

Of course, we're going to start breaking this rule very frequently in later lessons.

Previous Lesson: Polar Life Capsule
Next Lesson: Jump Instructions
Table of Contents