有没有办法访问makeActiveBinding安装的函数?

Jos*_*ien 12 r scoping

标题基本上都说明了一切.

如果我这样做......

makeActiveBinding("x", function() runif(2), .GlobalEnv)
x
# [1] 0.7332872 0.4707796
x
# [1] 0.5500310 0.5013099
Run Code Online (Sandbox Code Playgroud)

...那么我有什么方法可以检查x它与哪个功能相关联(如果没有,为什么不呢)?

(在这种情况下,我希望能够学习x被定义为function() runif(2).)

Rom*_*ois 11

随着一点点的涂鸦envir.c,我可以让这个工作:

#include <Rcpp.h>
using namespace Rcpp ;

#define HASHSIZE(x)      LENGTH(x)
#define HASHVALUE(x)    TRUELENGTH(x)

// [[Rcpp::export]]
SEXP get_binding_fun( std::string name, Environment env){
    SEXP symbol = Rf_install( name.c_str() );
    SEXP tab = HASHTAB(env) ;
    SEXP c = PRINTNAME(symbol);

    // finding the hash code for the symbol
    int hashcode = HASHVALUE(c) % HASHSIZE(tab);

    // get the value there from the hash table
    SEXP res = CAR( VECTOR_ELT(tab, hashcode ) ) ;

    return res ;
}
Run Code Online (Sandbox Code Playgroud)

将其保存到.cpp文件中,sourceCpp并将其与此R代码一起使用:

> makeActiveBinding("x", function() runif(2), .GlobalEnv)
> get_binding_fun("x", .GlobalEnv)
# function ()
# runif(2)
Run Code Online (Sandbox Code Playgroud)

  • 好吧 - 这真是令人印象深刻.谢谢! (2认同)