R scoping: disallow global variables in function

前端 未结 5 1474
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 23:37

Is there any way to throw a warning (and fail..) if a global variable is used within a R function? I think that is much saver and prevents unintended behaviours

5条回答
  •  生来不讨喜
    2020-12-08 23:50

    Another way (or style) is to keep all global variables in a special environment:

    with( globals <- new.env(), {
      # here define all "global variables"  
      sUm <- 10
      mEan <- 5
    })
    
    # or add a variable by using $
    globals$another_one <- 42
    

    Then the function won't be able to get them:

    sum <- function(x,y){
      sum = x+y
      return(sUm)
    }
    
    sum(1,2)
    # Error in sum(1, 2) : object 'sUm' not found
    

    But you can always use them with globals$:

    globals$sUm
    [1] 10
    

    To manage the discipline, you can check if there is any global variable (except functions) outside of globals:

    setdiff(ls(), union(lsf.str(), "globals")))
    

提交回复
热议问题