jdf / Processing.py-Bugs

A home for all bugs and feature requests about Python Mode for the Processing Development Environment.
41 stars 8 forks source link

Global variable cannot be accessed inside a function? #344

Closed pvzzombs closed 2 years ago

pvzzombs commented 2 years ago
cowcowcow = 0
startX = 0
startY = 0
boardWidth = 20
boardHeight = 20
tileSize = 30
board = [[[1,2]]]

def markMine(x, y):
    print(cowcowcow)
    cowcowcow = cowcowcow + 1

def setup():
    size(startX + boardWidth * tileSize, startY + boardHeight * tileSize)
    stroke(255)
    if 'cowcowcow' in globals():
        print('cowcowcow')

def draw():
    background(0, 0, 0)

def keyTyped():
    if key == ' ':
        markMine(0, 0)

Output:

UnboundLocalError: local variable 'cowcowcow' referenced before assignment

The global variable of interest here is named cowcowcow. Every time the spacebar is hit, the markMine function will then be called. Suprisingly, it cannot access the global variable cowcowcow. But in the function setup, the string cowcowcow is printed in the console, this means that the function setup can access it, but the function markMine cannot?

pvzzombs commented 2 years ago

Processing version: 3.5.4 Python mode for processing 3 3063

pvzzombs commented 2 years ago

Closing this issue. The issue is not a bug. The solution is to use global <global_variable_name> inside a function to be able use it. Sorry about this. It is my bad.