Version 1 of How was I invoked?

Updated 2009-01-19 14:43:01 by Cameron

Consider this example:

  proc show_invocation {} {
      return [info level -1]
  }


  proc a args {
      puts "Beginning of a."
      puts [show_invocation]
  }


  proc b args {
      a x y z
  }

  proc c args {
      b 1 2 3
  }

  c skip-to-my-lou

It has output

  Beginning of a.
  a x y z

In English words, this illustrates that a proc can report on the command-line which invoked it. In particular, this provides a base for introspection on the proc call-stack, coded in "Print proc sequence", "A basic debugger", "List the call stack", and perhaps elsewhere.


There's more, though: with 8.5, it becomes possible to write

  package require Tcl 8.5

  proc show_complete_invocation {} {
      set invoker [info level -2]
      set command [lindex $invoker 0]
      set body [info body $command]
      array set frame [info frame -2]
      set lines [split [read [open $frame(file)]] \n]
      return [lindex $lines [expr $frame(line) -1]]
  }


  proc a args {
      puts "Beginning of a."
      puts [show_complete_invocation]
  }


  proc b args {
      a x y z
      set x [a b c d]
  }

  proc c args {
      b 1 2 3
  }

  c skip-to-my-lou

The output of this script is

    Beginning of a.
          a x y z
    Beginning of a.
          set x [a b c d]

While this is a bit fragile, in that it requires considerably a few more lines to handle dynamic proc definitons, and other complications, it should at least hint at the possibilities of this sort of introspection.


enter categories here