Skip to content

Instantly share code, notes, and snippets.

@moodymudskipper
Last active June 13, 2022 21:54
Show Gist options
  • Select an option

  • Save moodymudskipper/bf8599cb5c539fb45b58d0c85f49c051 to your computer and use it in GitHub Desktop.

Select an option

Save moodymudskipper/bf8599cb5c539fb45b58d0c85f49c051 to your computer and use it in GitHub Desktop.

Revisions

  1. moodymudskipper revised this gist Jun 13, 2022. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion vassign.R
    Original file line number Diff line number Diff line change
    @@ -11,11 +11,12 @@ makeActiveBinding("v", local({
    count <<- 1
    e <<- exec_env
    }
    #
    # fetch function and body
    call <- sys.call(-1)
    caller_env <- sys.frame(-2)
    f <- eval(call[[1]], caller_env)
    calls <- as.list(body(f))[-1]
    # assign
    vpos <- which(sapply(calls, function(x) identical(x, quote(v))))
    value <- eval(calls[vpos - 1][[count]], exec_env)
    var <- as.character(calls[vpos + 1][count])
  2. moodymudskipper created this gist Jun 13, 2022.
    40 changes: 40 additions & 0 deletions vassign.R
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    makeActiveBinding("v", local({
    e <- NULL
    count <- 1

    function(value) {
    # increment or reinitialize counter
    exec_env <- sys.frame(-1)
    if(identical(e, exec_env)) {
    count <<- count + 1
    } else {
    count <<- 1
    e <<- exec_env
    }
    #
    call <- sys.call(-1)
    caller_env <- sys.frame(-2)
    f <- eval(call[[1]], caller_env)
    calls <- as.list(body(f))[-1]
    vpos <- which(sapply(calls, function(x) identical(x, quote(v))))
    value <- eval(calls[vpos - 1][[count]], exec_env)
    var <- as.character(calls[vpos + 1][count])
    assign(var, value, exec_env)
    }
    }), .GlobalEnv)


    test <- function() {
    1
    v
    x

    1 + 1
    v
    y

    c(x, y)
    }

    test()
    #> [1] 1 2