Python: cannot pass variable between functions?

I have an issue passing a variable from a function to another. Here is the exact code (level: Summit’s Gate):

def openDoor():
    door = self.findByType("door")[0]         # fixed
    self.say(door + " debug1")
    commandArchers(door)

def commandArchers(enemy):
    self.say(enemy + " debug2")
    archers = self.findByType("archer")
    for friend in archers:
        if not enemy:
            enemy = friend.findNearestEnemy()
            if enemy.type == "door":
                continue
        self.command(friend, "attack", enemy)

# command archers to open door
openDoor()

The output is:

> Outer Gate debug1
> undefined debug2

However, if I strip down the second function - which shouldn’t affect the passing of the variable -, it works as expected:

def openDoor():
    door = self.findByType("door")
    self.say(door + " debug1")
    commandArchers(door)

def commandArchers(enemy):
    self.say(enemy + " debug2")

# command archers to open door
openDoor()

Output:

> Outer Gate debug1
> Outer Gate debug2

Can anybody help me what’s going wrong here?

Well, first of all, self.findByType("door") returns a list. Archers can’t attack a list. Use something like self.findByType("door")[0] or self.findNearest(self.findByType("door")

Additionally, your commandArchers function only attacks something that is not a door. continue automatically skips a loop to the next iteration.

Thanks for your reply!

Yes, that was an oversight - I fixed that (by adding [0]). However, the problem is still there.


The intended logic is the following:

  • if I pass a target, they should attack it without question (skipping the if not enemy statement)
  • if I call the function without a target, they should select the nearest enemy if it’s not a door

This is a known issue ([1], [2]). The Python parser has a bug that treats function parameters that are reassigned inside the function body as undefined until the reassignment occurs (i.e. ignoring the value passed as argument).

You should be able to workaround the issue like this:

def commandArchers(enemy_):
    enemy = enemy_
    # ...
2 Likes

It works, it works! Thanks! :smile: