Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/nat-418/tutstack

An example Tcl package that implements a stack data structure.
https://github.com/nat-418/tutstack

Last synced: 13 days ago
JSON representation

An example Tcl package that implements a stack data structure.

Awesome Lists containing this project

README

        

# Tutstack

The following example of a Tcl package is sourced from the [official Tcl 8.5
documentation](https://www.tcl.tk/man/tcl8.5/tutorial/Tcl31.html).

This example creates a package which provides a stack data structure:

```
# Register the package
package provide tutstack 1.0
package require Tcl 8.5

# Create the namespace
namespace eval ::tutstack {
# Export commands
namespace export create destroy push pop peek empty

# Set up state
variable stack
variable id 0
}

# Create a new stack
proc ::tutstack::create {} {
variable stack
variable id

set token "stack[incr id]"
set stack($token) [list]
return $token
}

# Destroy a stack
proc ::tutstack::destroy {token} {
variable stack

unset stack($token)
}

# Push an element onto a stack
proc ::tutstack::push {token elem} {
variable stack

lappend stack($token) $elem
}

# Check if stack is empty
proc ::tutstack::empty {token} {
variable stack

set num [llength $stack($token)]
return [expr {$num == 0}]
}

# See what is on top of the stack without removing it
proc ::tutstack::peek {token} {
variable stack

if {[empty $token]} {
error "stack empty"
}

return [lindex $stack($token) end]
}

# Remove an element from the top of the stack
proc ::tutstack::pop {token} {
variable stack

set ret [peek $token]
set stack($token) [lrange $stack($token) 0 end-1]
return $ret
}
```

To make a Tcl package, run this command:

```
$ echo 'pkg_mkIndex .' | tclsh
```

You should now have a

And some code which uses it:

```
package require tutstack 1.0

set stack [tutstack::create]
foreach num {1 2 3 4 5} { tutstack::push $stack $num }

while { ![tutstack::empty $stack] } {
puts "[tutstack::pop $stack]"
}

tutstack::destroy $stack

```

You should now have a `pkgIndex.tcl` file that looks like this:

```
# Tcl package index file, version 1.1
# This file is generated by the "pkg_mkIndex" command
# and sourced either when an application starts up or
# by a "package unknown" script. It invokes the
# "package ifneeded" command to set up package-related
# information so that packages will be loaded automatically
# in response to "package require" commands. When this
# script is sourced, the variable $dir must contain the
# full path name of this file's directory.

package ifneeded tutstack 1.0 [list source [file join $dir tutstack.tcl]]
```