Scripting tutorial #6: Using the Stack

What is the Stack?

When programmers talk about a "stack", they are referring to a special portion of memory that has been set aside to temporarily hold small amounts of information. But, unlike named variables or proper objects, a stack is just a pile of data. Although programmers could create their own miniature stacks for their programs to use, every program is given a stack of its own. Likewise, a stack is set aside for you to use in your scripts.

The stack is important, as it's the primary way for a program (or your scripts) to share information between its various parts. In fancier languages, programmers don't usually need to manipulate the stack themselves. Instead, the language they're using handles it for them. As mentioned before, the scripting language used by this editor is barely a language at all, so everything must be handled manually.

Of course, if you're not using functions, you don't need to worry about the stack. Regular variables will be fine.

How is the Stack used?

While the stack can hold a lot of information, you can only access the top of the stack. It's sort of like a stack of books or papers: you can remove whatever's on top, or you can place something else onto the stack, but you can't access anything in the middle of the pile. These actions are known as "popping" or "pushing" the stack, so the commands for this are POP and PUSH.

Of the two, only PUSH takes a parameter - the value to add to the stack. POP always places the current value into the .RESULT variable, so no parameters are needed.

Things to remember about using the Stack

While the stack is useful for passing information between functions, there is a limit to how much information can be held by it. Attempting to place more than 256 values on the stack will trigger a "stack overflow" error, halting your script. By the same token, attempting to retrieve more values than are present will trigger a "stack underflow" error.

To prevent either error from occurring, be careful to ensure that you're always POPing and PUSHing an equal number of times. For example, if you PUSH five values, then you should POP five values to keep things even. That said, don't worry about clearing the stack before your script ends; anything left in it will just be discarded.

 

On to the next tutorial page -->

<-- Back to the previous tutorial page

Project Hosted by
Download Mike\'s Sprite Editor