Arrays in memory



  • Hi, I'm trying to use arrays in memory but I can't figure out what is wrong with the code. It seems the array is constantly destroyed every tick.

    Source.prototype.followUsage = function(opts) {
        if(this.ticksToRegeneration == 1)
        {
            if(!this.room.memory.usage)
            {
                console.log("first pass");
                this.room.memory.usage = new Array();
            }
            var id = this.id;
            var t =null;
    
            if(this.room.memory.usage[id] == undefined){
                console.log("should pass only once here");
                this.room.memory.usage[id] = new Array();
                t = this.room.memory.usage[id];
                console.log(t.toString());
                t.push(0);
            }
            t.push((this.energyCapacity - this.energy) / this.energyCapacity * 100);
            /*if(t.length >10){
                t.slice(1,9);
            }*/
            console.log("source "+id+" usage "+t[t.length-1]+"%");
            console.log("source "+id+" previous usage "+t[t.length-2]+"%");
            console.log(t.toString());
            // should not be necessary, anyway does not work
            this.room.memory.usage[id] = t;
        }
    };
    

    Every time it is fired, I get only 2 values in my array, 0 and the current %.



  • Just a quick mention: I heard a lot of these situations before simply because they had some code later that clears out memory.



  • You initialize t to null and then only assign it a value when this.room.memory.usage[id] is undefined. So when it _isn't_twill remain null and at the end of the function you set this.room.memory.usage[id] value to null again. The value gets destroyed every other tick.



  • Hi, Thanks for the tip Toolmaker it was a proper assumption, but actually with tests I found the problem:
    I create an Array instead of an Object, so indexing with the id which is a string is not possible. I changed the inital usage variable to be a new Object() and now it rocks 🙂