Published on

lua闭包

Authors
  • avatar
    Name
    Ushen
    Twitter
local a = function()
    local i = 0
    local function b()
        print("i = ", i)
        i = i + 1
    end
    return b
end

local b = a()

b()
b()

以上函数,i是函数a的内部变量,将函数a的返回值,赋值给函数b

执行两次函数b,此时的运行结果是

i = 0
i = 1

函数a的内部变量i,没有被清除掉,在下次调用b时依旧生效。

假如换一种写法,函数a的return b 改成 return b(),直接返回内部函数b的执行结果

此时的运行结果是

i = 0
i = 0

因为函数a的内部函数b未被引用,直接引用了返回的值,所以外部函数调用完之后,没有了联系,里面的变量被当成垃圾清理掉。

当a的内部函数b被引用时,由于闭包的存在,a的内部变量没有被清理掉