You need a stack solution which provides more than just push and pop for your Tcl script.
In the last post, I discussed the use of Tclx package’s lvarpop and lvarpush to turn an ordinary list into a stack. In this installment, I will discuss the struct::stack package which provides more features.
Using the struct::stack Package
package require struct::stack # Create a stack and push 3 items struct::stack myStack puts "\nCreate a stack and push 3 items" myStack push peter paul mary # The stack is just an ordinary Tcl list. Show it. puts "Stack contents: [myStack get]"; # mary paul peter puts "Stack size: [myStack size]"; # 3 # Peek and pop some items and display: puts "\nPeek and Pop:" puts "Peek 1 item: [myStack peek]"; # mary puts "Peek 2 items: [myStack peek 2]"; # mary paul puts "Pop 1 item: [myStack pop]"; # mary puts "Pop 2 items: [myStack pop 2]"; # paul peter puts "Stack size: [myStack size]"; # 0 # Stack managements puts "\nStack Management:" myStack push mickey michael peter davy myStack push john paul george ringo puts "Stack contents: [myStack get]"; # ringo ... mickey puts "Stack size: [myStack size]"; # 8 puts "Reduce to 3 items, which discards: [myStack trim 3]" puts "Stack contents: [myStack get]"; # peter michael mickey puts "Stack size: [myStack size]"; # 3 myStack clear puts "Clear the Stack" puts "Stack size: [myStack size]"; # 0 # Done, destroy the stack to reclaim memory myStack destroy
The Output:Create a stack and push 3 items Stack contents: mary paul peter Stack size: 3 Peek and Pop: Peek 1 item: mary Peek 2 items: mary paul Pop 1 item: mary Pop 2 items: paul peter Stack size: 0 Stack Management: Stack contents: ringo george paul john davy peter michael mickey Stack size: 8 Reduce to 3 items, which discards: ringo george paul john davy Stack contents: peter michael mickey Stack size: 3 Clear the Stack Stack size: 0
- Line 4: create a new stack and name it ‘myStack’
- Lines 6: push 3 items into the stack ‘myStack’.
- Line 9: the get command returns the contents of the stack, with the left-most item being the “top of stack”.
- Lines 13-18: demonstrate the peek and pop command. Note that the peek command does not alter the stack. Also note the order of items when peeking and popping more than one items.
- Lines 27-28: the stack at this time has 8 items, the trim command reduce its size down to 3 and return the discarded items. Note the order of the discarded items. The next line show the contents of the stack, which only has 3 items as the result of the trim command.
- Lines 31-33: demonstrate the clear command to reset the contents of the stack.
The struct::stack package offers the full-feature stack data type which you can use in your Tcl script. I hope this post helps you to get yourself familiar with the stack and consequently feel comfortable using it instead of rolling your own solution.