Search code examples
pythonvariablesglobal-variablesprocessing

global variable not updating (Processing.py)


I'm using processing.py to make an application for drawing simple lines this is my code:

pointsList =[ ]
points = []


def setup():
    global pointsList, points
    size(400,400)
    stroke(255)
    strokeWeight(5)

def draw():
    global pointsList, points
    background(0)
    for points in pointsList:
        draw_points(points)
    draw_points(points)


def keyPressed():
    global pointsList, points
    if key == 'e':
        try:
            pointsList.append(points)
            points = [] #<--- this right here not updating
        except Exception as e:
            print(e)
        print(pointsList)

def mouseClicked():
    global points
    print(points)
    points.append((mouseX,mouseY))


def draw_points(points):
    for i in range(len(points)-1):
        draw_line(points[i],points[i+1])

def draw_line(p1,p2):
    line(p1[0],p1[1],p2[0],p2[1])

at one point I want to clear my "points" array but it's not updating

what is causing this?


Solution

  • Problem is in different place because you use the same name points in function draw() in loop for points so it assigns last element from pointList to points

    You have to use different name in draw() - ie. items

    def draw():
        global pointsList, points
    
        background(0)
    
        for items in pointsList:  # <-- use `items`
            draw_points(items)    # <-- use `items`
    
        draw_points(points)
    

    pointsList = []
    points = []
    
    def setup():
        global pointsList, points
    
        size(400,400)
        stroke(255)
        strokeWeight(5)
    
    def draw():
        global pointsList, points
    
        background(0)
    
        for items in pointsList:  # <-- use `items`
            draw_points(items)    # <-- use `items`
    
        draw_points(points)
    
    
    def keyPressed():
        global pointsList, points
    
        if key == 'e':
            try:
                pointsList.append(points)
                points = []
            except Exception as e:
                print(e)
    
            print(pointsList)
    
    def mouseClicked():
        global points
    
        points.append((mouseX,mouseY))
        print(points)
    
    def draw_points(points):
        for i in range(len(points)-1):
            draw_line(points[i], points[i+1])
    
    def draw_line(p1, p2):
        line(p1[0], p1[1], p2[0], p2[1])