Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env bash
- # stack constructor: stack name [ value ]*
- #
- # This creates a global stack object and a collection of functions of the form
- # name.method which are defined below.
- #
- # Example:
- #
- # $ source split_stack
- # $ stack name
- # $ name.push 20 30 40
- # $ echo $( name.dump )
- # 20 30 40
- # $ echo $( name.tos )
- # 40
- # $ name.pop
- # $ echo $( name.dump )
- # 20 30
- #
- # This type of use is also valid:
- #
- # $ object=name
- # $ $object.push 50
- # $ echo $( $object.dump )
- # 20 30 50
- function stack( ) {
- local name=$1
- shift
- unset stack_$name
- declare -a -g stack_$name
- object_create "$name" "_stack_"
- $name.push "$@"
- }
- # name.forget
- #
- # Destroys the named stack
- function _stack_forget( ) {
- local name=$1
- unset stack_$name
- object_destroy "$name"
- }
- # name.copy new
- #
- # Creates a copy of the named stack as new
- function _stack_copy( ) {
- local name=$1
- local new_name=$2
- stack "$new_name"
- $new_name.push $( $name.dump )
- }
- # name.push [ value ]*
- #
- # Pushes values to the stack.
- function _stack_push( ) {
- local -n stack=stack_$1
- shift
- while (( $# > 0 ))
- do
- local value=$1
- local count=${#stack[@]}
- stack[$count]=$value
- shift
- done
- }
- # name.tos
- #
- # Outputs the current top of stack
- function _stack_tos( ) {
- local -n stack=stack_$1
- local count=${#stack[@]}
- let index="count - 1"
- (( index < 0 )) && return 1
- echo "${stack[$index]}"
- }
- # name.pop
- #
- # Removes the current top of stack
- function _stack_pop( ) {
- local -n stack=stack_$1
- local count=${#stack[@]}
- let index="count - 1"
- (( index < 0 )) && return 1
- unset stack[$index]
- }
- # name.depth
- #
- # Outputs the number of items on the stack
- function _stack_depth( ) {
- local -n stack=stack_$1
- echo ${#stack[@]}
- }
- # name.dump
- #
- # Convenience function to output the contents of the stack
- function _stack_dump( ) {
- local -n stack=stack_$1
- for value in "${stack[@]}"
- do
- echo "$value"
- done
- }
- # Object functions
- # object_create name pattern
- function object_create( ) {
- local name=$1
- local pattern=$2
- local methods=$( declare -F | grep " $pattern" | sed "s/^declare -f $pattern//" )
- for method in ${methods[@]}
- do
- method_create "$name.$method" "$pattern$method" "$name"
- done
- }
- # object_destroy name
- function object_destroy( ) {
- local name=$1
- local methods=$( declare -F | grep " $name\." | sed "s/^declare -f //" )
- for method in ${methods[@]}
- do
- unset -f "$method"
- done
- }
- # method_create name function args ...
- function method_create( ) {
- local name=$1
- shift
- eval "$name( ) { "$@" \"\$@\" ; }"
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement