Last active
August 29, 2015 13:58
-
-
Save wenLiangcan/10135400 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function newCounter() | |
local i = 0 | |
return function() -- anonymous function | |
i = i + 1 | |
return i | |
end | |
end | |
c1 = newCounter() | |
print(c1()) --> 1 | |
print(c1()) --> 2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def new_counter(): | |
i = [0] | |
def nested(): | |
i[0] += 1 | |
return i[0] | |
return nested | |
>>>c = new_counter() | |
>>>c() | |
1 | |
>>>c() | |
2 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def new_counter(): | |
i = 0 | |
def nested(): | |
i += 1 | |
return i | |
return nested | |
c = new_counter() | |
c() | |
--------------------------------------------------------------------------- | |
UnboundLocalError Traceback (most recent call last) | |
<ipython-input-3-1f2bdb17cf98> in <module>() | |
----> 1 c() | |
<ipython-input-1-6662aa87dc2a> in nested() | |
2 i = 0 | |
3 def nested(): | |
----> 4 i += 1 | |
5 return i | |
6 return nested | |
UnboundLocalError: local variable 'i' referenced before assignment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment