dougeff wrote:
LDA abs,X. Interesting. Let me see if I can pseudo code that...
LDA #var 3
PHA
LDA #var 2
PHA
LDA #var 1
PHA
TSX
STX stackP ;stack pointer
JSR subR
Leave the TSX for the subroutine, so it is only done there and not in every place that calls it. The $1XX numbers will be a little different because of stepping over the return address, but that doesn't add any overhead. If you need to save and restore X, that can be done in the subroutine too. You'd normally push it onto the stack before doing the TSX, which will again change the $1XX numbers (but it's still no problem).
Quote:
var1 = $0100
var2 = $0101
var3 = $0102
subR:
LDX stackP
LDA var1, X ;to access var1
...
LDA var2, X ;to access var 2
...
LDA var3, X ;to access var 3
Yes; but var1, var2, and var3 in the subroutine will be local variables, separate (and for clarity, probably deserving different names) from var1, var2, and var3 above in the calling routine. You can do all the instructions on them that have the abs,X addressing mode, like ADC, ROR, ORA, STA, INC, LDY, etc..
Quote:
I'm not sure this is preferred to any other method. Personally, I've been using zp variables (called temp1, temp2, etc) to pass to subroutines.
Then you have to be awfully careful where they get used so that one routine doesn't use one of the temporary variables and overwrite a value that another pending routine still needs. Been there, done that. The better use you can make of the stack(s), the more you can stay out of that kind of trouble, and the fewer global variables (ZP or otherwise) you'll need.
In the book "Thinking Forth" by Leo Brodie (which is really more about programming philosophy, and its material is not just for applying Forth), there's a section called, "The Problem With Variables." On page 211 there's a cute cartoon I'm tempted to scan and post here (although I'm sure it would be a copyright violation) showing a young man in a body cast in a hospital bed, and a young, slim, curvy woman explaining to him, "Shot from a cannon on a fast-moving train, hurtling between the blades of a windmill, and expecting to grab a trapeze dangling from a hot-air balloon...I told you Ace, there were too many variables!"
Another good reason to keep it on the stack and avoid excessive variable usage is re-entrancy. If the subroutine gets interrupted by an IRQ or NMI, and the ISR needs that subroutine, keeping it re-entrant by having the stack-based local variables will keep you out of trouble. Recursion is possible too (where the subroutine calls itself, over and over until the exit condition is met so it can unwind its way out), but most users here are pretty unlikely to even use recursion.