Wednesday, November 16, 2011

The Stack

The best part about REXX (after PARSE, of course) is the stack.  Knowing how to exploit the stack can save you mountains of trouble.  Once you get to appreciate the power of the stack, it opens doors to a world of capabilities.  Remember when we used to write line-mode dialogs: prompt then PULL the response?

say "Enter the dataset name:"
pull dsn

But you can't do that if there's already something on the stack.  You can't do that if there might be something on the stack.  Just in case, you should always phrase the above as

"NEWSTACK"
say "Enter the dataset name:"
pull dsn
"DELSTACK"

The same is true if you're dealing with a subroutine that returns its answer on the stack (my favorite mode of inter-module communication).  Let's say you have a subroutine that does some function for you and returns its result via the stack:

"NEWSTACK"
"CKSTATE" volid
pull state
if state = "MULT" then
   do queued()
      pull state   area
   parse value  volst.0+1   state  area    with,
                zz          volst.zz   1  volst.0  .
   end 
else volst.1 = state   "00"
"DELSTACK"

That is, if your subroutine returns more than one value, the first line of the returned stack is "MULT" and all the returned values follow.  If there's only one returned value, it's on line number 1.

The beauty of "NEWSTACK"/"DELSTACK" is that you can protect any material you've squirreled away against damage by other data that also needs to use the stack.  This is especially important when that 'other data' comes from the keyboard in response to a prompt.

Lastly, the use of "NEWSTACK"/"DELSTACK" guarantees that the current stack is empty.  If you want to be 100% sure you're getting a response from the keyboard and no place else, "NEWSTACK" is it.  When I want to put out multiple pages of data (HELP-text, for instance, or a screenful of output) and wait for the user's permission to go to the next page, I insert this line where I want to wait for the user to finish reading:

"NEWSTACK"; pull ; "CLEAR" ; "DELSTACK"

(Your installation may use some other routine to clear the screen.  Just substitute your local flavor.)

No comments:

Post a Comment