I am trying to run a block of code only if the varaibles are not valid strings (length > 0, and not undefined). Based on this SO post I think Im doing it right, but this runs every time. What am I doing wrong here?
if (creep.memory.sourceid ||creep.memory.depositLoc||creep.memory.sourceType)
{
creep.memory.sourceid = getSourceMinWorkers(creep);
creep.memory.sourceType='energy';
creep.memory.depositLoc=getClosestDepositLoc(creep.memory.sourceid,creep.memory.sourceType);
console.log(creep.name," harvesting ",creep.memory.sourceType," at: ",creep.memory.sourceid," depositing at: ",creep.memory.depositLoc);
}
output of console.log:
H1_1 harvesting energy at: 81a61f68f5eb4057223b05b2 depositing at: a7633d25d9058f616ab8a0f3
H1_1 harvesting energy at: 1649baad43f736c9fc13d2ad depositing at: a7633d25d9058f616ab8a0f3
You are checking with a OR (||
) operator. That means that the conditional will run if either of the conditionals is true (non-empty in case of strings).
You have this conditional:
if (creep.memory.sourceid || creep.memory.depositLoc || creep.memory.sourceType) {
It means that if creep.memory.sourceid
is set OR creep.memory.depositLoc
is set OR creep.memory.sourceType
is set, it will run.
I see that you are logging the 3 variables with this line:
console.log(creep.name," harvesting ",creep.memory.sourceType," at: ",creep.memory.sourceid," depositing at: ",creep.memory.depositLoc);
The data is logged each time the block is ran, and I see that the 3 parameters are non-empty strings, so the code is working as expected.
By your code, I think that the expectation is to run the code only if 2 parameters are set but there's no location, so you have to switch your OR operators to AND (&&
), which will pass if ALL 3 conditionals are true. Also you will have to check if the location is empty, like this:
if (creep.memory.sourceid && !creep.memory.depositLoc && creep.memory.sourceType) {
// Notice the exclamation ^ up there
This way the code block will be ran if there's a source id AND if DON'T(!
) has a deposit location AND if has a source type. Notice the exclamation before the location parameter. This means that is the negation of the value.