Stack in Small Basic?
Published Feb 12 2019 03:32 PM 380 Views
Iron Contributor
First published on MSDN on Oct 27, 2014

Authored by Nonki Takahashi


A stack is a special memory of a computer program.  In Small Basic, Stack object  supports stack.  Today, I' d like to introduce Stack.


In Small Basic forum, there was a question How do I give a variable more than one number posted by Steven Jelsma.  To save many data, there are two methods.  One is Stack.  The other is Array.  Array can be accessed in random way with index.  But Stack is accessed sequentially in LIFO (last-in first-out) order.  I made a sample animation as a Small Basic program LFD194 .



LIFO is something special.  But sometimes it's useful.  So I will introduce three programs using Stack.


The first sample is the tower of HANOI .  This is a very simple sample because the tower is just LIFO.


The second sample is local variable.  Small Basic doesn't have local variable.  Especially recursive call destroys global variables.  So to call subroutine recursively Stack is used to save variables.  Following subroutine DrawTree calls itself.  And the variable distance needs to be kept.  Whole program is listed in Small Basic Getting Started Guide: Appendix A: Fun Samples .



Sub DrawTree

If ( distance > 0 ) Then

Turtle . Move ( distance )

Turtle . Turn ( angle )


Stack . PushValue ( "distance" , distance )

distance = distance - delta

DrawTree ( )

Turtle . Turn ( - angle * 2 )

DrawTree ( )

Turtle . Turn ( angle )

distance = Stack . PopValue ( "distance" )


Turtle . Move ( - distance )

EndIf

EndSub


The third sample is for searching subdirectories.  Litdev wrote details about this in a TechNet Wiki article Small Basic: Stack Basics .



See Also


Version history
Last update:
‎Feb 12 2019 03:32 PM
Updated by: