面向对象编程中, 很重要的概念之一是隐含的 “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)