This page is a mirror of Tepples' nesdev forum mirror (URL TBD).
Last updated on Oct-18-2019 Download

Peeking into the stack?

Peeking into the stack?
by on (#210932)
I would like to peek into the stack to get a value N bytes from the top of the stack.
But I cannot find an example for this.

Is there some syntax like in NESASM similar to NASM's where you can get a value at an address that is the sum of a register plus a certain value?
Similar to this:

lda [S+10]
Re: Peeking into the stack?
by on (#210933)
The plain 6502 has no stack-indexed instructions, unfortunately.

You basically have to save or discard the contexts of X, use the TSX instruction, and use instructions that use absolute-indexed addressing like LDA $0100,X

This is one of the many reasons that cc65 uses a separate software stack for function parameters, instead of using the same stack as the one that holds return addresses.
Re: Peeking into the stack?
by on (#210937)
On 6502 (NES), you would indeed use TSX and index into the stack that way. Just watch for wraparound if there aren't already $10 bytes pushed to the stack.

On 65816 (Super NES), the stack behaves more like an ordinary index register in that you can use LDA $10,S, or even LDA ($10,S),Y.
Re: Peeking into the stack?
by on (#210943)
The most common way to read the Nth element from the top of the stack is:
  lda $100+N, x
Re: Peeking into the stack?
by on (#210954)
See my 6502 stacks treatise. (Notice it's "stacks," plural, as it includes virtual stacks, and is not limited to just the page-1 hardware stack.) There's all you'd ever want to know about 6502 stacks there, plus more, in 19 chapters plus appendices. Indexing into the page-1 hardware stack is introduced in chapter 5, at .