Search code examples
rtrace

Trace function which is declared inside another function


I have the following code:

abc <- function() {
    def <- function() { }
    def_enter <- function() { print("def_enter") }
    def_exit <- function() { print("def_exit") }
    trace(def, def_enter, exit = def_exit)
    def()
}

abc_enter <- function() { print("abc_enter") }
abc_exit <- function() { print("abc_exit") }

trace(abc, abc_enter, exit = abc_exit)

abc()

I expect the output like this:

> abc()
Tracing abc() on entry 
[1] "abc_enter"
Tracing def() on entry
[1] "def_enter"
Tracing def() on exit
[1] "def_exit"
Tracing abc() on exit 
[1] "abc_exit"
NULL

But get such output:

> abc()
Tracing abc() on entry 
[1] "abc_enter"
Tracing function "def" in package "base"
Tracing abc() on exit 
[1] "abc_exit"
NULL

Is it possible to get output which I expect? How I can fix the code above?


Solution

  • You need to specify the environment on which the function in trace is called. Just mention it in the argument where of trace in the definition of abc:

    abc <- function() {
        def <- function() { }
        def_enter <- function() { print("def_enter") }
        def_exit <- function() { print("def_exit") }
        trace(def, def_enter, exit = def_exit, where=environment())
        def()
    }
    

    And by calling abc, you will get the expected result:

    #>abc()
    #Tracing abc() on entry 
    #[1] "abc_enter"
    #Tracing function "def" in package ".GlobalEnv"
    #Tracing def() on entry 
    #[1] "def_enter"
    #Tracing def() on exit 
    #[1] "def_exit"
    #Tracing abc() on exit 
    #[1] "abc_exit"
    #NULL