Global Variables Not Getting Scoped In Class Method?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gentel

I have the following code:

var binaryGrid = [];

var miners = set();

class Miner:
    func _init(x,y):
        self.x = x;
        self.y = y;
    func moveMiner():
        self.x = abs(self.x % binaryGrid[0].length);
        self.y = abs(self.y % binaryGrid.length);
    
        if self.x == len(binaryGrid) - 1 or self.y == len(binaryGrid[0]) - 1:
            miners.remove(this);

So you see that binaryGrid is defined at the global scope. However, that if statement at the bottom is causing the following error:

Identifier not found: binaryGrid

Why does this class method not see the ostensibly global-scoped variable? What can I do to get this to work?

Thanks in advance.

:bust_in_silhouette: Reply From: Zylann

binaryGrid is not on global scope, it is on class member scope of your script (script = class too, even if they have no name). In fact, global variables don’t exist in Godot.

Then you defined a class which is nested in that script, but that doesn’t mean it can access to member variables of the enclosing class, it’s not the way it works in Godot. Subclasses are just like any other class, they don’t have a magical scope being included.

You have to pass this grid to your Miner as a dependency if you want to access it, for example you pass it in the _init(x, y, mine) and store it in a member var of Miner.
Or, as I see in your script, you could pass the instance of the enclosing script to your Miner instance, so you can write mine.binaryGrid or mine.miners.remove(self).

Note 1: this is undefined, use self
Note 2: my proposal above would work if your mine is a node, or an Object. If it was a resource or a Reference (scripts extending nothing are), it would produce potential cyclic references.