+1 vote

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:

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.

in Engine by (13 points)

1 Answer

+1 vote

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.

by (28,731 points)
edited by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.