We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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?
Answers
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:
Otherwise you're gonna need to move it into setup(), and declare g w/
global
before its assignment: