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
| DATA | Type | Description |
|---|---|---|
aStack | Array | Internal array holding stack items |
Methods
| Method | Description |
|---|---|
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
- FWStack methods that accept variable arguments (New, Push) work with both Harbour and xHarbour. On xHarbour, they accept an array parameter instead of varargs.
- The
Peek()method with no argument returns the top item without removing it. With a positive argument n, it looks n positions from the top (1 = top). With a negative argument, it counts from the bottom (-1 = bottom). - Push() and Clear() return Self, enabling method chaining:
oStack:Clear():Push( 1, 2, 3 ):Push( 4 ). - Pop() returns nil when the stack is empty -- test with
oStack:Size() > 0before popping.