Skip to content
Prev 38143 / 63424 Next

Reference classes

On 23 October 2010 00:52, Jon Clayden <jon.clayden at gmail.com> wrote:
Unfortunately, I'm having difficulty working out the accessor function
approach. I've looked in the Rcpp package for examples, but it doesn't
seem to use this feature. If I define

Foo <- setRefClass("Foo", fields=list(bar=function (newBar) {
                                            if (missing(newBar)) bar
                                            else stop("bar is read-only") }),
                          methods=list(barExists=function ()
print(exists("bar"))))

then I can't access the value of "bar" due to infinite recursion.
Using ".self$bar" in the accessor produces the same effect.
[1] TRUE
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
Error: evaluation nested too deeply: infinite recursion / options(expressions=)?

I can guess why this is happening (accessing "bar" within the accessor
calls itself), but how can I get at the value of "bar" within the
accessor without this occurring?

The other problem is that I can't even set a value at the time of
creation of the object, viz.
Error in function (newBar)  : bar is read-only

Is there a way to test whether "bar" has already been set in the
accessor, so that I can allow it to be set once? (I know lock() allows
this, but it would be useful to be able to replicate the effect using
accessors, so that it can be generalised further where needed.)
Clearly, exists("bar") doesn't do this, as seen above -- presumably
because it sees the method rather than the field, or there is some
default value.

Thanks in advance,
Jon