Table of Contents

闭包


一个简单的例子

我的理解就是返回一个函数,“函数访问UpValue”

function GetFunction()
    local iCount = 0
 
    return function()
        iCount = iCount + 1
        print('This is '..iCount..'th Times You Call the Function!')
    end
end
 
-- 调用一个函数,其返回一个函数
local F = GetFunction()
 
-- 调用这个返回的函数
for i=1,3 do F() end
 
-- 重新返回一遍函数呢?
local anotherF = GetFunction()
 
anotherF() anotherF() -- 计数重新开始了
F() F() -- 注意,这里可能和预期不同,F的数据没有被重置
-- 也就是说:F和anotherF访问的是不同的位置的数据,iCount是独立的
This is 1th Times You Call the Function!
This is 2th Times You Call the Function!
This is 3th Times You Call the Function!
This is 1th Times You Call the Function!
This is 2th Times You Call the Function!
This is 4th Times You Call the Function!
This is 5th Times You Call the Function!

绑定函数参数

Bind = function(self,func)
    if self == nil then
        return function(...) return func(...) end
    else
        return function(...)
            return func(self,...)
        end
    end
end
 
Data = {
    iCount = 0,
}
 
function Data:Add(iAdd)
    self.iCount = self.iCount + iAdd
    print('Count = '..self.iCount)
end
 
Data:Add(1)
 
kOutAdd = Bind(Data, Data.Add)
kOutAdd(2)
Count = 1
Count = 3