A bug with functions or more bad coding?

(I’m using Javascript and this has happened on Bonemender and Oasis.)

Is there some rule against starting your code with functions? I tried to build a couple functions to keep things tidy and kept getting an odd error:

The code:

function healUp() {
    var pal = this.findNearest(this.findFriends());
    if (this.canCast("regen", pal) && this.distanceTo(pal) < 10) {
        this.cast("regen", pal);
}}

The error:

Upper or lowercase problem. Try this.findFriends()
Line 2: undefined is not a function.

That was from Bonemender. The error on Oasis was the same except it was for a this.say.
So can anyone tell me: bad coding or ghost in the machine?

Thanks!

There is an issue with regards to accessing this inside the function. I don’t know the proper answer for how to do it though.

1 Like

inside the function the scope of ‘this’ changes to the function itself.

solve this by defining the variable self at the top of the file then change all of this.something to self.something

var self = this;
function healUp() {
    var pal = self.findNearest(self.findFriends());
    if (self.canCast("regen", pal) && self.distanceTo(pal) < 10) {
        self.cast("regen", pal);
}}

or pass this into your healUp function call wherever that is.

function healUp(self) {
    var pal = self.findNearest(self.findFriends());
    if (self.canCast("regen", pal) && self.distanceTo(pal) < 10) {
        self.cast("regen", pal);
}}

healUp(this);
2 Likes

Hello. I am trying to change the global variable “nearest” inside the function. And then use it outside the function. But my Hero performs strange jumps. Could you help me, please?

var hero = this;
var enemies;
var nearest;

function jumpToArcher(types){
    enemies = hero.findByType(types);
    if(enemies){
        nearest = hero.findNearest(enemies);
        return true;
    }
    return false;        
}

loop {
    if(this.isReady("jump") &&
    (jumpToArcher("fangrider") ||
    jumpToArcher("shaman") ||
    jumpToArcher("thrower"))){
        this.jumpTo(nearest);   
    }
    enemies = this.findEnemies();
    nearest = this.findNearest(enemies);
    if(nearest) this.attack(nearest);
}

Thanks!

The findByType method always returns an array, and arrays are always truthy values in JavaScript. Try changing if(enemies){ to if(enemies.length){

1 Like

Thank you! Now it works! :smiley:

1 Like