How to create R functions with private variables? -
how create set of r functions access same private variable?
let's want create readsetting(key)
, writesetting(key,value)
functions both operate on same hidden list settings
. if try so...
local( { settings <- list() readsetting <<- function ( key ) settings[[key]] writesetting <<- function ( key, value ) settings[[key]] = value } )
...then readsetting
, writesetting
not visible outside of local
call. if want them visible there, have first assign
readsetting <- writesetting <- null
outside local
call. there must better way, because code isn't dry if have in 2 different ways variables public.
(the context of work i'm developing r package, , code in auxiliary file loaded main file via source
.)
this question related how limit scope of variables used in script? answers there not solve problem.
you can simulate somthing using r6class package , following rough code:
privates <- r6class("privates", public=list( readsetting = function(key) { private$settings[[key]] }, writesetting = function(key,value) { private$settings[[key]] <<- value } ), private=list( settings = list() ) ) <- privates$new() a$writesetting("a",4) a$readsetting("a")
directly reading o setting a$setting
not work.
Comments
Post a Comment