When/how/where is parent.frame in a default argument interpreted?

主宰稳场 提交于 2019-12-01 06:21:58

问题


Truth be told, I'm just being lazy here, but perhaps someone could someday profit from the answer being here.

Say I define a function like:

fn<-function(envir=parent.frame())
{
    #do something with envir
}

My question is: what might I expect to be the content of envir?

Context: I had a rather long function f1 that contained a call to parent.frame. Now, I want to extract part of that function (containing the parent.frame call) into a new helper function f2 (which will then be called by f1), and I want to be sure that f1 does the same as it did before.


回答1:


Default arguments are evaluated within the evaluation frame of the function call, from which place parent.frame() is the calling environment. envir's value will thus be a pointer to the environment from which fn was called.

Also, just try it out to see for yourself:

debug(fn)
fn()
# debugging in: fn()
# debug at #2: {
# }
Browse[2]> envir
# <environment: R_GlobalEnv>


来源:https://stackoverflow.com/questions/15504960/when-how-where-is-parent-frame-in-a-default-argument-interpreted

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!