Page 1 of 1

Peeking into the stack?

Posted: Fri Dec 29, 2017 3:16 pm
by Midnightas
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:

Code: Select all

lda [S+10]

Re: Peeking into the stack?

Posted: Fri Dec 29, 2017 3:20 pm
by lidnariq
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?

Posted: Fri Dec 29, 2017 5:29 pm
by tepples
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?

Posted: Fri Dec 29, 2017 6:33 pm
by tokumaru
The most common way to read the Nth element from the top of the stack is:

Code: Select all

  tsx
  lda $100+N, x

Re: Peeking into the stack?

Posted: Fri Dec 29, 2017 11:34 pm
by Garth
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 http://wilsonminesco.com/stacks/stackaddressing.html .