Skip to content

Instantly share code, notes, and snippets.

@wenLiangcan
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wenLiangcan/10135400 to your computer and use it in GitHub Desktop.
Save wenLiangcan/10135400 to your computer and use it in GitHub Desktop.
function newCounter()
local i = 0
return function() -- anonymous function
i = i + 1
return i
end
end
c1 = newCounter()
print(c1()) --> 1
print(c1()) --> 2
def new_counter():
i = [0]
def nested():
i[0] += 1
return i[0]
return nested
>>>c = new_counter()
>>>c()
1
>>>c()
2
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