闭包

Lua 是一种功能性编程语言,并且全面支持闭包。创建新函数时,任何局部变量都会与该函数实例绑定。闭包可用于创建迭代器函数,以及为面向对象编程创建私有变量。

使用闭包的其中一个最简单示例是,创建一个可用于 for 循环的迭代器函数。

function counter(i)
    local x=0
    return function()
        x=x+1
        if x > i then return null end
        return x
    end
end

在上面的示例中,每次调用 counter 函数时,都会创建一个新的迭代器函数。局部变量 x 和 i 的值与迭代器函数的该实例绑定,不可从任何其他函数中访问。函数参数始终被视为局部变量,任何使用 local 关键字声明的变量也是如此。counter 函数可以与 for 循环结合使用,如下所示。

sum=0
for i in counter(5) do
    for j in counter(5) do
        sum = sum + j
    end
end

闭包概念还可用于支持面向对象编程的数据隐私,如以下示例所示。

function newAccount(balance)
    local t={}

    t.deposit = function(amount)
        balance = balance + amount
        return balance
    end

    t.withdraw = function(amount)
        balance = balance - amount
        return balance
    end

    t.getBalance = function() 
        return balance 
    end

    return t
end

account = newAccount(1000)
account.deposit(100)
account.withdraw(500)
balance = account.getBalance()

使用元表(请参阅元表)来创建对象比使用闭包更为常见,但元表不像使用闭包一样能够很好地实现数据隐私。