Peeking into the stack?

Discuss technical or other issues relating to programming the Nintendo Entertainment System, Famicom, or compatible systems. See the NESdev wiki for more information.

Moderator: Moderators

Post Reply
Midnightas
Posts: 1
Joined: Fri Dec 29, 2017 3:08 pm

Peeking into the stack?

Post 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]
lidnariq
Posts: 11432
Joined: Sun Apr 13, 2008 11:12 am

Re: Peeking into the stack?

Post 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.
tepples
Posts: 22708
Joined: Sun Sep 19, 2004 11:12 pm
Location: NE Indiana, USA (NTSC)
Contact:

Re: Peeking into the stack?

Post 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.
User avatar
tokumaru
Posts: 12427
Joined: Sat Feb 12, 2005 9:43 pm
Location: Rio de Janeiro - Brazil

Re: Peeking into the stack?

Post 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
Garth
Posts: 246
Joined: Wed Nov 30, 2016 4:45 pm
Location: Southern California
Contact:

Re: Peeking into the stack?

Post 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 .
http://WilsonMinesCo.com/ lots of 6502 resources
Post Reply