register_method {bandicoot} | R Documentation |
Register method for an object environment
Description
This function register a function as a method of an object environment.
Usage
register_method(
env,
...,
container_name = "..method_env..",
self_name = "self",
class_name = env$..type..
)
Arguments
env |
Environment. Object environment. |
... |
Named Functions. Functions needs to be provided in named format,
like |
container_name |
Character. Name of the container. Methods will be executed inside this container. |
self_name |
Character. Name of the self reference. Methods needs to use this name to access the object environment. |
class_name |
Character. Name of the class of the object environment.
This is important for |
Details
Methods will be executed inside a container, which is a child
environment of the parent of the object environment. Thus, methods can not
access variables of the object environment directly, but can access
variables of the parent of the object environment directly. The designed
way for methods to access the object environment is by using the name
"self", this name can be changed by specifying a string in self_name
.
The default name of the container is "..method_env..". This also can be changed
by specifying a string in container_name
. An object can have multiple
containers, but every container is recommended to contain only one self
reference.
Method needs to be provided as a = function() 1
, where a
is the name of
the method and the right hand side of the equal sign is the function.
Warning will be raised if the container contains contents other than the
self reference.
Value
Return the object itself.
Examples
a <- function() self$x
e <- new.env()
e$x <- 1
# Register the method `aa` for environment `e` with `self_name = "self"`
register_method(e, aa = a, self_name = "self", class_name = "test")
# There is an environment `..method_env..` in the environment `e`
names(e)
# The container is empty (except `self`)
names(e$..method_env..)
# `self` is a reference to `e`
identical(e, e$..method_env..$self)
# The method `aa` will be evaluated in the container
identical(environment(e$aa), e$..method_env..)
# Therefore, `self$x` is a reference to variable `x` of the environment `e`
e$aa()