Can't find a way to check if a memory attribute exist or not before accessing it.



  • I get the number of harvester in each of my room with the code :

        let creepsInRoom = spawn.room.find(FIND_CREEPS);
        ....
        var numberOfHarvesters = _.sum(creepsInRoom, (c) => c.memory.role == 'harvester');
    

    But each time an enemy come to one of my room and doesn't have a creep.memory.role attribute, I got a NPE. I can't find a way to check if an attribute exist in memory before trying to access it.

    (I'm a JS newbie)



  • I think your problem is not that there isn't a role - undefined == 'harvester' just gives you false. The problem is that there isn't any memory for that creep, since it doesn't belong to you.

    There are two ways you can fix this:

    1. If you only want your own creeps to be in creepsInRoom, you can change FIND_CREEPS to FIND_MY_CREEPS.
    2. If you want both your creeps and hostile creeps to be in creepsInRoom, you can change c.memory.role == 'harvester' to c.my && c.memory.role == 'harvester'. (The double && means that the second part will only be checked if the first part is also true. If the first part is false, the answer will be false.)
    👍


  • Thanks for that clear and short answer 😉 Have a god day Sir Yoshi I think all will be ok with your help.