Variable scope in S3 generics

I have the following snippet:

y <- 1
g <- function(x) {
  y <- 2
  UseMethod("g")
}
g.numeric <- function(x) y
g(10)
# [1] 2

I do not understand why there is access yto g.numeric <- function(x) y. As far as I understand, scope is only in the definition of the general (g <- ...). Can someone explain to me how this is possible?

+4
source share
1 answer

A description of this behavior can be found on the help page. ?UseMethod

UseMethod creates a new function call with arguments consistent as they appear. Any local variables defined before calling UseMethod are retained.

Thus, any local variables defined in the calling UseMethodfunction are passed to the next function in the form of local variables. You can see it with

g.numeric <- function(x) ls()  #lists all variables in current environment
g(10)
# [1] "x" "y"
g.numeric(10)
# [1] "x"
+4
source

Source: https://habr.com/ru/post/1589343/


All Articles