Search code examples
roopclass-methodr6class-properties

Call method from method inside same class


I am trying to create a flow structure in an object that is based on a class. I have 4 methods (where 3 methods should be called from the method [run()].

Question:

Should you be able to call a method from another method assuming you are in the same object/class.

What works:

I am capable of running following methods one-by-one with correct output:

game$part_1()

game$part_2()

game$part_3()

Errors:

When I issue [game$run()] I get following error:

Error in part_1() : could not find function "part_1"

Wanted behaviour:

I want the object to be able to run methods trigger by other methods (all methods being in the same class).

if (!"package:R6" %in% search()) {
  library(R6)
}


# Class


Game <- R6Class("Game",

    public = list(

        # Properties:

        a     = 0,
        b     = 0,
        sum   = 0,


        # Functions:

        run = function() {
            part_1()
            part_2()
            part_3()
        },

        part_1 = function() {
            self$a = 10
            return(self$a)
        },

        part_2 = function() {
            self$b = 20
            return(self$b)
        },

        part_3 = function() {
          self$sum = self$a + self$b
          return(self$sum)
        }

     )

)
# Instantiate an object base on a class.
game <- Game$new()

# Run function that runs through all other functions.
game$run()

Solution

  • You should be able to just add self to the method calls:

    run = function() {
                        self$part_1()
                        self$part_2()
                        self$part_3()
                      }