Skip to content
Prev 40499 / 63424 Next

Reference Class error message: may be caused by lazy evaluation?

Good catch.

Here's the problem.  To save space and time, reference methods are not 
all copied to every object in the class.  Instead, the methods are 
copied in when first accessed.   Methods are functions which use the 
object as their environment.  So that is the sense in which "lazy 
evaluation" is involved.

If a method calls another method (add() calling addOne() in your 
example), then the method for the `$` operator knows to copy over that 
method (addOne).  (The second of my examples below shows this.)  But if 
the method _refers_ to another method without calling it, the code 
analysis does not currently catch the reference.

We can fix that, although it's a little subtle. Meanwhile, your 
showself() is a good workaround.

For anyone interested, the code below illustrates.

One point of style.  I would suggest saving the generator object and 
calling its $new() method, as below, rather than treating the reference 
class as an S4 class.  The result is identical AFAIK, but the style is 
more typical of such OOP languages.

John

---------------------------
 > tc <-  setRefClass("testclass", fields = list(a = "numeric"),
+             methods = list(
....
+               ))
 > t1 <- tc$new(a=1)
 > ss = t1$show
 > ss
Class method definition for method show()
function ()
{
     print(addOne)
}
<environment: 0x10188d5f8>
 > ev = environment(ss)
 > ev
<environment: 0x10188d5f8>
 > t1
An object of class "testclass"
<environment: 0x10188d5f8>  # <<<< same environment
 > objects(ev)
[1] "a"    "show"  #<<<< not addOne, though
 > t1$addOne
Class method definition for method addOne()
function ()
{
     a <<- a + 1
     print(a)
}
<environment: 0x10188d5f8>
 > objects(ev)
[1] "a"      "addOne" "show"  # <<<< now addOne is there
On 6/8/11 4:38 PM, Tengfei Yin wrote: