Lua 中的面向对象编程

面向对象编程中, 很重要的概念之一是隐含的 “this” 指针, 即有一个变量指代了自身.在 lua 中, 使用 “self” 代表 “this”.

--[[ (1)
基本代码.
--]]
Account = {balance = 0}
function Account.withdraw(v)
    Account.balance = Account.balance - v
end

--[[ (2)
使用 (1) 中的 Account.
调用 a.withdraw(100.0) 时, 函数内部应当调用 a.balance = a.balance - 100.0,
而函数定义为 Account.balance = Account.balance - v, 所以出错.
--]]
Account.withdraw(100.0)
print(Account.balance)           --> -100

a = Account
a.withdraw(100.0)                --> error

--[[ (3)
对 (1) 的改进, 即重写 withdraw() 函数.
这里明确指明了 self 参数, 即调用者.
--]]
Account = {balance = 0}
function Account.withdraw(self, v)
    self.balance = self.balance -v
end

--[[ (4)
使用 (3) 中代码.
--]]
a = Account
a.withdraw(a, 100.0)
print(a.balance)                 --> -100
print

--[[ (5)
在面各对象编程中, "self" 一般是隐含的, 在 Lua 中要隐含 self 指针, 需要另一个':' 语法来定义表中的函数.
--]]
Account = {balance = 0}
function Account:withdraw(v)
    
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值