py5coding / py5generator

Meta-programming project that creates the py5 library code.
https://py5coding.org/
GNU General Public License v3.0
52 stars 13 forks source link

Another setup() "hidden settings() disentanglement feature" edge case with global statements #59

Closed villares closed 2 years ago

villares commented 2 years ago

Related to: https://github.com/hx2A/py5generator/issues/40

Sometimes, not always, global statements don't work in setup().

Minimal example using imported mode:


def setup():
    size(500, 500)

    global b
    b = height / 2
    global a 
    a = width / 2

def draw():
    circle(a, b, 100)

Result:

Python 3.8.10 (/home/villares/miniconda3/envs/py5coding/bin/python3.8)
>>> %cd '/home/villares/Área de trabalho'
>>> %Run /home/villares/miniconda3/envs/py5coding/lib/python3.8/site-packages/py5_tools/tools/run_sketch.py '/home/villares/Área de trabalho/gt.py'
File "/home/villares/Área de trabalho/gt.py", line 14, in draw
    12   def draw():
    13       circle(a, b, 100)

NameError: name 'b' is not defined
hx2A commented 2 years ago

Finally have this fixed!

The code behind the setup() magic is a delicate balance between reworking the code to create new settings() and setup() functions and proper error messages. A lot of work has gone into making sure py5's error messages point to the user's code with the correct line numbers when an exception is raised. This is difficult to achieve because the actual code that is executed is different from what the user wrote. All of this needs to work correctly for py5bot and run_sketch in addition to regular sketches, as you did in your example.

Fixing this gave me a chance to revisit the code for this and simplify things. I uncovered a bunch of other hidden problems (or perhaps I stirred up new problems with my first attempt at a fix). In any case, the code is simpler now and seems to work correctly for everything I throw at it.