How to modify Objects in memory



  • I am trying to add data to an existing memory Object but can't get it to work. From what I know screeps stores objects in memory rather than arrays.However, also the normal object methods like .push() don't work for adding new entries to the object. Now I am trying to assign the existing memory to an object variable, maybe that will work. Does anyone know how this is supposed to be done? Code:

    if (creep.room.memory.isVisited == false){
                console.log("in new room");
                var roomSources = creep.room.find(FIND_SOURCES);
                var roomData = {remoteRoom: creep.room.name, sources: roomSources};
                var existingData = Object.assign(Game.rooms[creep.memory.home].memory.roomData);
                existingData.push(roomData);
                Game.rooms[creep.room.home].memory.roomData = existingData;
    }


  • Usually you get quick help on discord in #world-help

    The Memory object is stringified to JSON at the end of your tick, so you can only add objects that can be stringified. I never add any GameObjects, instead I add their id and resolve them later with Game.getObjectById. So I would map the ids of the roomSources: sources: _.map(roomSources, s=>s.id).

    var existingData = Game.rooms[creep.memory.home].memory.roomData;

    assuming that roomData is an array and initialized somewhere else, you should be able to push to it.

    Later you can access the sources from Memory by mapping them back again:

    var roomSources = _.map(roomData.sources, s=>Game.getObjectById(s));

    Keep in mind that getObjectById only works for objects that your bot can see. You would need a creep in the remote room to see the sources. That's why I also like to store the position for pathing without sight.



  • Thanks Xenofix for the reply. Yeah, as you can see I was working on a script form a scout unit that goes into neighboring rooms to store their room names and sources. So the initial problem was how to combine the existing stored data with the newly accquired data from a new room and I had some trouble figuring that out. Maybe that could use some reworking to only store source Ids as an array. Actually I wanted to store the room data as an array containing arrays (Array of Arrays) so I can access roomData[index].sources[index].id and so on.



  • You can also copy attributes into an object. e.g. sources: _.map(roomSources, s=>{id:s.id,pos:s.pos})



  • It seems I found a solution. Now I am just directly accessing memory at a specific index. It's possible to simply write memory.roomData[index] = some_data; and it will create a new object index at that position.