Problem with global variables

edited April 2016 in Python Mode

So, I have defined a class, DotGrid, and I want to have a global DotGrid variable, which I use in draw, like this:

g = DotGrid( 10 )
for i in range( 0, 100 ):
    g.add_dot( Dot( random.randint( 0, width - 1 ), random.randint( 0, height - 1 ) ) )

def setup():
    size( 700, 700 )
    background( 255 )
    fill( 0 )
    noStroke()

def draw():
    g.display()

Whenever I try to run this, there’s a weird error code — it points to somewhere in the definition of DotGrid where I use width, and it says, “NameError: global name 'width' is not defined”. So, I can’t put the definition of g outside setup(), but I can’t put it in it either — if I defined g in setup(), I couldn’t use it in draw(). Can you please help me figure out how to avoid both of these problems so I can use a global DotGrid variable?

Tagged:

Answers

  • edited April 2016 Answer ✓

    Variables like width, height and some few others are initialized properly once sketch reaches setup().

    If your class DotGrid use such variables within its __init__() constructor, you can instantiated at the top of your sketch:

    g = DotGrid(10)
    
    def setup():
        # ...
    

    Otherwise you're gonna need to move it into setup(), and declare g w/ global before its assignment:

    def setup():
        size(700, 700)
        fill(0)
        noStroke()
    
        global g
        g = DotGrid(10)
    
Sign In or Register to comment.