OpenResty学习笔记(八) lua高阶之面向对象编程,openrestylua


在 Lua 中,我们可以使用表和函数实现面向对象。将函数和相关的数据放置于同一个表中就形成了一个对象。
请看文件名为 account.lua 的源码:

local _M = {}

local mt = { __index = _M }

function _M.deposit (self, v)
    self.balance = self.balance + v
end

function _M.withdraw (self, v)
    if self.balance > v then
        self.balance = self.balance - v
    else
        error("insufficient funds")
    end
end

function _M.new (self, balance)
    balance = balance or 0
    return setmetatable({balance = balance}, mt)
end

return _M

引用代码示例:

local account = require("account")

local a = account:new()
a:deposit(100)

local b = account:new()
b:deposit(50)

print(a.balance)  --> output: 100
print(b.balance)  --> output: 50

上面这段代码 “setmetatable({balance = balance}, mt)”, 其中 mt 代表 { __index = _M } ,这句话值得注意。根据我们在元表这一章学到的知识,我们明白,setmetatable 将 _M 作为新建表的原型,所以在自己的表内找不到 ‘deposit’、’withdraw’ 这些方法和变量的时候,便会到 __index 所指定的 _M 类型中去寻找。
Lua是个面向过程的语言, 但通过Metatable可以模拟出面向对象的样子. 其关键就在于__index这个域. 他提供了表的索引值入口. 这很像重写C#中的索引器, 当表要索引一个值时如table[key], Lua会首先在table本身中查找key的值, 如果没有并且这个table存在一个带有__index属性的Metatable, 则Lua会按照__index所定义的函数逻辑查找. 仔细想想, 这不正为面向对象中的核心思想继承, 提供了实现方式么. Lua中实现面向对象的方式非常多, 但无论哪种都离不开__index。

相关内容

    暂无相关文章