Created
April 4, 2022 16:29
-
-
Save moodymudskipper/69cdb8d8b21f8faa986c07ed821f1049 to your computer and use it in GitHub Desktop.
invisible attributes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
set_invisible_attr <- function(x, ...) { | |
x_chr <- as.character(substitute(x)) | |
pf <- parent.frame() | |
if(bindingIsActive(x_chr, pf)) { | |
env <- environment(activeBindingFunction(x_chr, pf)) | |
args <- list(...) | |
env$closure$attrs[names(args)] <- args | |
return(x) | |
} | |
closure <- new.env() | |
closure$attrs <- list(...) | |
closure$value <- x | |
rm(list = x_chr, pos = pf) | |
makeActiveBinding(x_chr, env = pf, function (v) { | |
if(missing(v)) return(closure$value) | |
closure$value <- v | |
invisible(closure$value) | |
}) | |
invisible(NULL) | |
} | |
invisible_attr <- function(x, which) { | |
x_chr <- as.character(substitute(x)) | |
pf <- parent.frame() | |
if(!bindingIsActive(x_chr, pf)) return(NULL) | |
env <- environment(activeBindingFunction(x_chr, pf)) | |
env$closure$attrs[[which]] | |
} | |
foo <- bar <- 42 | |
set_invisible_attr(foo, evil = 666) | |
identical(foo, bar) | |
foo <- bar <- 43 | |
invisible_attr(foo, "evil") | |
invisible_attr(bar, "evil") | |
identical(foo, bar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment