Hello,
I just want to know why my code it’s not working.
Can you help me ?
// Manage the queue without mistakes.
// Useful string constants.
var PHRASE_IN = " in";
var PHRASE_OUT = " out";
var IDLE = "idle";
// The list of workers.
var workers = hero.findByType("peasant", hero.findFriends());
// Use this array to control the worker queue.
var queue = [];
while(true) {
// Iterate through all the workers:
for(var i = 0; i < workers.length; i++){
var worker = workers[i];
}
// If the worker's "status" property is "idle":
if(worker.status == "idle"){
// Say the worker's name and the string " in":
hero.say(worker + " in");
// Add the worker to the end of the queue:
queue.append(worker);
}
var item = hero.findNearestItem();
// If the item exists and the queue isn't empty:
if(item && queue.length > 0){
worker = queue[0];
// Say the name of the first worker in the queue
// with the string " out":
hero.say(worker + " out");
// Remove (shift) the first worker from the queue:
queue.pop(0);
}
}
@totodej did you write this code yourself? Because I see several errors in the structure, for example the for loop isn’t right, since the } isn’t in the right place (should be at the end). Then the worker variable is missing a “var” in front, as well as the queue.append mistake. These mistakes shouldn’t be made by a programmer who has been coding in javascript all the way through the mountain campaign.
for(var i = 0; i < workers.length; i++){
var worker = workers[i];
}
// If the worker's "status" property is "idle":
if(worker.status == "idle") {
// and so on
}
I thought (maybe as you ) the variable worker will be undefined. BUT NO!!!
Important: JavaScript does not have block scope. Variables introduced with a block
are scoped to the containing function or script, and the effects of setting them persist
beyond the block itself. In other words,block statements do not introduce a scope.
Although "standalone" blocks are valid syntax, you do not want to use standalone
blocks in JavaScript, because they don't do what you think they do, if you think they
do anything like such blocks in C or Java.
and the same thing for python
In Python, the scoping rules are fairly simple and elegant: a block is either a
module, a function body or a class body. Within a function body, names are
visible from the point of their definition to the end of the block (including
nested blocks such as nested functions). That's for local names, of course;
global names (and other nonlocal names) have slightly different rules,
but that's not pertinent to our discussion. The important point here is:
the innermost possible scope is a function body. Not a for loop body. Not
a with block body. Python does not have nested lexical scopes below the
level of a function, unlike some other languages (C and its progeny,
for example).
That is exactly what i said. The for loop’s end bracket wasn’t right. Pretty sure totodej beat the level already tho because they already posted a new question about another level.