UtterAccess HomeUtterAccess Wiki

Welcome Guest ( Log In | Register )

Custom Search
Edit Discussion
> Stack    

A simple class that provides a Stack type collection. Many people find stacks useful for creating procedure call stacks for error handling.

Push Pushes a value onto the stack
Pop Removes the top value from the stack
Value The value of the current top element
Index The current 0-based position in the stack (the top element)
ReportDelimValueList Attempts to create a stack list for return in a delimited string. Useful only for basic datatypes



Option Compare Database
Option Explicit
Option Base 0

' provides a basic Stack object for VBA.
' if index = -1 then no objects are on the stack
' v1.0 - initial release
' 2011-04-27

Private m_Value As Variant  'RO
Private m_Index As Long 'RO

Private stack() As Variant

Public Sub Push(val As Variant)

 If Not IsInit() Then
   'this is the first item to do on this stack
   ReDim stack(0)
   stack(0) = val
   Index = 0
 ElseIf Index = UBound(stack) Then
   'the index needs to stretch the stack
   ReDim Preserve stack(Index + 1)
   stack(Index + 1) = val
   Index = Index + 1
   stack(Index + 1) = val
   Index = Index + 1
 End If
 Value = stack(Index)
End Sub

Public Sub Pop()
 If Index > -1 Then
   Index = Index - 1
   If Index = -1 Then
       Value = Null
       Value = stack(Index)
   End If
 End If
End Sub

Public Function ReportDelimValueList(Optional Delimiter = ";") As String
 'attempts to give a delmited list of the stack values to the user
 Dim l As Long, s As String
 For l = 0 To Index
   s = s & ";" & stack(l)
 ReportDelimValueList = Replace(s, Delimiter, "", 1, 1)
End Function

Private Function IsInit() As Boolean
 On Error Resume Next
 Dim x As Long
 x = UBound(stack)
 IsInit = IIf(Err.Number = 9, False, True)
End Function

Public Property Get Index() As Long
 Index = m_Index
End Property
Private Property Let Index(l As Long)
 m_Index = l
End Property

Public Property Get Value() As Variant
 If Index = -1 Then Exit Property
 Value = m_Value
End Property
Private Property Let Value(v As Variant)
 m_Value = v
End Property

Private Sub Class_Initialize()
 Index = -1
End Sub

Creative Commons License
Stack by UtterAccess Wiki is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Editing and revision of the content is freely encouraged; for details, see Expected Usage.

Edit Discussion
Custom Search

Thank you for your support!
This page has been accessed 6,943 times.  This page was last modified 23:03, 1 February 2014 by Jack Leach. Contributions by Glenn Lloyd  Disclaimers