默认参数中的parent.frame何时/如何/在何处解释? [英] When/how/where is parent.frame in a default argument interpreted?

查看:169
本文介绍了默认参数中的parent.frame何时/如何/在何处解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说实在的,我只是在这里很懒,但是也许有人有一天可以从这里的答案中受益.

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
}

我的问题是:我期望envir的内容是什么?

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

上下文:我有一个相当长的函数f1,其中包含对parent.frame的调用.现在,我想将该函数的一部分(包含parent.frame调用)提取到一个新的辅助函数f2中(然后由f1调用),并且我想确保f1的功能与以前相同.

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.

推荐答案

对默认参数进行评估

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>

这篇关于默认参数中的parent.frame何时/如何/在何处解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆