FWStack

Source: source/classes/fwstack.prg

FWStack implements a classic LIFO (Last-In, First-Out) stack data structure. It stores items in an internal array and provides push, pop, and peek operations. The constructor and Push() method accept variable-length argument lists, allowing multiple items to be added in a single call. FWStack is useful for undo/redo operations, expression evaluation, and any scenario requiring last-in-first-out data management.

Key DATA Members

DATATypeDescription
aStackArrayInternal array holding stack items

Methods

MethodDescription
New( item1, item2, ... )Create a stack initialized with the given items (bottom to top)
Push( item1, item2, ... )Push one or more items onto the top of the stack. Returns Self for chaining.
Pop()Remove and return the top item from the stack. Returns nil if the stack is empty.
Peek( n )Return the nth item from the top without removing it. n defaults to 1 (the top). Negative n indexes from the bottom (e.g., -1 is bottom). Returns nil if the index is out of range.
Size()Return the number of items in the stack
Clear()Remove all items from the stack. Returns Self for chaining.

Example: Push/Pop Values

#include "FiveWin.ch"

function Main()

   local oStack := FWStack():New()

   // Push multiple items
   oStack:Push( 10, 20, 30, 40, 50 )

   ? "Stack size:", oStack:Size()       // 5

   // Peek at top item without removing
   ? "Top item:", oStack:Peek()         // 50

   // Peek at item 2 from top (0-indexed from the top)
   ? "Second from top:", oStack:Peek( 2 )  // 40

   // Pop items
   while oStack:Size() > 0
      ? "Popped:", oStack:Pop()
   end

   ? "Stack is empty:", oStack:Size() == 0  // .T.

   // Initialize with items
   oStack := FWStack():New( "apple", "banana", "cherry" )
   ? oStack:Pop()   // "cherry"
   ? oStack:Pop()   // "banana"
   ? oStack:Pop()   // "apple"
   ? oStack:Pop()   // nil (empty)

return nil

Notes

See Also