Stack - Falmouth-Games-Academy/comp310-wiki GitHub Wiki

Stack

The Basics of the Stack

Within computer science, the stack is an abstract data type 1(https://en.wikipedia.org/wiki/Stack_(abstract_data_type)), which allows for data to be stored in the order it was added and then removed in the same order. A very common way to explain the stack is to look at it as if it were a stack of plates, with plates being added on top of each other and preventing any previous plates being removed out of order.

The use of the stack can vary though it's commonly used for functions like backtracking through steps in a program or undoing certain actions if the user made a mistake. This isn't the only use for the stack with it's particular kind of storage being used for efficiency 2(https://en.wikipedia.org/wiki/All_nearest_smaller_values) and memory management.

The 6502 and Stacks

The 6502 implements a descending Stack, starting at $FF and growing downward as data is added into the array. The 6502 is also referred to as an empty stack, which simply means the stack pointer is pointing to an empty space in the array. Once a value has been added the stack then points to the next available slot. It's worth noting that it's good practice to reset your stack pointer to $FF when calling reset to prevent overflowing the stack. 3(https://wiki.nesdev.com/w/index.php/Stack)

4(https://upload.wikimedia.org/wikipedia/commons/b/b4/Lifo_stack.png)![Stack Image ](https://upload.wikimedia.org/wikipedia/commons/b/b4/Lifo_stack.png)

Implementing Stacks in Assembly

Pushing to the stack

_init:
  ldx #$ff	; Set the stack pointer to $FF
  txs		; (e.g. $01FF)

_pushstack:
  lda #$e0	; Push value $e0 on to the stack.
  pha		; $01FF now contains $e0, and S is now $FE.

  ldy #$bb	; Push value $bb on to the stack.
  tya
  pha		; $01FE now contains $bb, and S is now $FD.

  txa
  pha		; Push value $ff (from the _init routine) on to the stack.
		; $01FD now contains $ff, and S is now $FC.

3(https://wiki.nesdev.com/w/index.php/Stack)

Code rundown:

LDX - Load X Index With Memory.

LDA - Load Accumulator With Memory.

LDY - Load Y Index With Memory.

PHA - Push Accumulator

TYA - Transfer Y to A

TXA - Transfer X to A

5(http://www.6502.org/tutorials/6502opcodes.html#PHA)

Pulling from the stack

_pullstack:
  pla		; Pull the value $ff off the stack, and put it into the accumulator.
  tax		; S now becomes $FD.

  pla		; Pull the next value ($bb) off the stack, and put it into the X register.
  tay		; S now becomes $FE.

  pla		; Pull $e0 off the stack, and put it into the Y register.
		; S now becomes $FF -- which is where we started!

3(https://wiki.nesdev.com/w/index.php/Stack)

Code Rundown:

PLA - Pull Accumulator

TAX - Transfer A to X

TAY - Transfer A to Y

5(http://www.6502.org/tutorials/6502opcodes.html#PHA)

References