A question about some codes


#1
> def commandTroops():
>     for friend in friends:
>         enemy = friend.findNearestEnemy()
>         if enemy:
>             hero.command(friend, "attack", enemy)

When i use friend.findNearestEnemy(), in some levels it works, and some levels it says can’t read protected property. I don’t know why. does somebody know the logic behind this?


#2

Did you define friends?


#3

@Seojin_Roy_Lee Yes, i define friends in the loop while true.


#4

That won’t work. A variable that is defined inside one loop or function cannot be seen in or used in another loop or function. In the function that you have shown here, you must define the variables you use inside it.


#5

Yep. you will need to pass “friends” through the function, like:

def commandTroops(friends):
     for friend in friends:
         enemy = friend.findNearestEnemy()
         if enemy:
             hero.command(friend, "attack", enemy)

Notice the fact the “friends” is in the function, and when you run the function, it will need to look something like this:

commandTroops(friends)

Hope that helps!


#6

and you have to define friends before you activate commandTroops(friends).


#7

Yep. I just assumed that was already done, but good point :smiley: