function newCounter ()
local i = 0
return function () -- anonymous function
i = i + 1
return i
end
end
c1 = newCounter()
print(c1()) --> 1
print(c1()) --> 2
c2 = newCounter()
print(c2()) --> 1
print(c1()) --> 3
print(c2()) --> 2
這裡anonymous function使用了一個local variable i 去記count。但照理說已經離開了這個function的scope,這個i應該被清掉,而不是作用像個static variable。
這個i被視為一個up value 或又稱作是external local variable。
而當assign一個新的newCounter時,又會產生一個新的i。
"Technically speaking, what is a value in Lua is the closure, not the function. The function itself is just a prototype for closures."
因為 lua 的function被視為是first-class values。根據wiki
所謂的first-class function:
"函數可以作為別的函數的參數、函數的返回值,賦值給變量或存儲在資料結構中。"
我想這種return anonymous function的做法像c1,c2 都被稱作是closure。
參考自
http://www.lua.org/pil/6.1.html
2015年9月18日 星期五
closure
之前在C#中聽過這個,但一直不知道是幹嘛用的。
現在又在lua中看到,想徹底了解一下。
訂閱:
張貼留言
(
Atom
)
沒有留言 :
張貼留言