Reliably holding ECMAScript 6 class instances in memory



  • I ran into an issue that seemed like a bug when trying to store an instance of a class in Memory. Here's some minimal code to reproduce it:

    main.js:

    class Doggo {
      bark() {console.log('woof')}
    }

    module.exports.loop = function () {
      if (Game.time % 5 == 0) {
        Memory.pooch = new Doggo();
        console.log("Single pooch instanceof Doggo (same tick as created): " + (Memory.pooch instanceof Doggo));
        Memory.pooch.bark();
      }
      else {
        console.log("Single pooch instanceof Doggo: " + (Memory.pooch instanceof Doggo));
        Memory.pooch.bark();
      }

    }

     

    And sample output:

    [3:39:52 AM] Single pooch instanceof Doggo (same tick as created): true
    [3:39:52 AM] woof
    [3:39:52 AM] Single pooch instanceof Doggo: false
    [3:39:52 AM] TypeError: Memory.pooch.bark is not a function
    at Object.module.exports.loop:13:22
    at __mainLoop:1:15387
    at eval:2:4
    at Object.c.runCode:6:13734
     
    What seems to be happening is that an instance of class is relegated to just being an object on game ticks after it is created.
    Could someone with more experience explain why this might be happening? Does Screeps actually support ECMAScript 6 classes?

     


  • Culture

    Anything that is put into memory is run through json stringify and then back through json parse. 

    Instead of saving classes in memory you need to save the data to initialize them.