Reputation: 480
I am Programming a lot in Python and just started playing around with Screeps and Javascript.
In the tutorial, this code is used to move a creep to an energy resource and harvets it:
if(creep.store.getFreeCapacity() > 0) {
var sources = creep.room.find(FIND_SOURCES);
if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources[0]);
}
}
And the creep will do exactly that. However, in my intuition, the creep should not start harvesting because it is only told to move there. Is that something unique to how the objects are defined in Screeps, or something I am misunderstanding JavaScript.
I also tried to move the creep to the source without the if statement to check whether it will automatically harvest, but it does not do it.
Upvotes: 1
Views: 225
Reputation: 4208
The harvest code can also be pulled apart instead of putting it in a single line. Maybe that will make it clear for you.
if(creep.harvest(sources[0]) == ERR_NOT_IN_RANGE) {
creep.moveTo(sources[0]);
}
This part tells the creep to harvest and only after that evaluates the result of that harvest. The documentation says the method returns a constant result which can be checked.
Pulling this code apart a bit, it looks like this:
let harvestResult = creep.harvest(sources[0]);
if (harvestResult == ERR_NOT_IN_RANGE) {
creep.moveTo(sources[0]);
}
Now it's a bit clearer that the method is always called and evaluated after.
Upvotes: 2