Skip to content

Instantly share code, notes, and snippets.

@wenLiangcan wenLiangcan/counter.lua
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.