stanekam
stanekam

Reputation: 4030

Accessing the environment a function is defined in, from outside the function

Let's say that I have a closure in R that looks something like the following:

closure <- function(driver=system.file("java/driver.jar", package="fake"),
                    db_username=.getDb_username(), 
                    db_password=.getDb_password(), 
                    db_name=.getDb_name(),
                    tunnel="ssh command"){
  system(tunnel)
  drv <- JDBC("db.jdbc.Driver",
              driver,
              identifier.quote="`")
  db_con <- dbConnect(drv, db_name, db_username, db_password)

  runQuery <- function(sql_query, ...){
    sql_query <- processQuery(sql_query, ...)

    return(.dbRunQuery(db_con, sql_query, dbGetQuery))

  }
  return(runQuery)
}

Then I run the following code:

closure_return <- closure()

Now, I want to access db_con from closure_return. Is this possible? If so how?

Note that I don't want to change closure in any way. If changing closure is the only way that's fine, but please try to provide an answer that does not involve changing closure.

Please let me know if you need any clarification or if I'm using the word "closure" incorrectly.

Upvotes: 1

Views: 54

Answers (1)

stanekam
stanekam

Reputation: 4030

I'm silly.

Answer found here: http://adv-r.had.co.nz/Functional-programming.html#closures

More information can also be found at ?environment.

I can simply run environment(closure_return) and access the vars there.

Upvotes: 1

Related Questions