5 ms·
EDIT: re-reading your comment I think I see now you were agreeing with me. :-) Leaving this here as elucidation. That python code throws UnboundLocalError, whi
by intrepidhero 4y ago
EDIT: re-reading your comment I think I see now you were agreeing with me. :-) Leaving this here as elucidation.
That python code throws UnboundLocalError, which seems like what it should do to me. If you move total = 0 to before def incr(x): then incr closes over the local total variable. Every call to make_counter returns a new counter with its own state.
The equivalent Lua defines total as a global (whether total = 0 is above or below). Multiple instances of incr are all changing the same global variable. That doesn't like the intended behavior.
- intrepidhero 4y agoWhoops, actually the python version only works if you move total AND add a nonlocal keyword. https://docs.python.org/3/reference/simple_stmts.html?highlight=nonlocal#nonlocal https://docs.python.org/3/reference/simple_stmts.html?highli...
- bhk 4y agoThe existence of `nonlocal` is an indictment of the local-by-default design. (Parenthetically, for completeness, I should note that this is a problem only when the language supports mutable variables or, more precisely, mutable captures or "upvalues", which I think are also a bad idea, but that's another bag of worms for another day.)