您的位置:首页 > 编程语言 > Lua

Lua五:面向对象基础

2021-10-04 15:24 651 查看

       面向对象有三个核心特征:类,继承,私有性。基于这三方面,介绍Lua的面向对象的编程和实现原理(没介绍的会在之后的随笔介绍)。从很多意义上讲,Lua语言中的一张表就是一个对象。使用参数self是所有面向对象语言的核心点。

先看下一段代码,这是一个简单表达账户储存和提取的代码:

Account = {balance = 0}

function Account.withdraw ( v)

Account.balance = Account.balance – v

end

Account.withdraw ( 100.00 )

a,Account = Account, nil

a.withdraw ( 100.00)                       --> ERROR!

这里代码会出现错误,这是因为目前withdraw函数只针对特定对象即Account工作。对象a不能使用withdraw函数。因此,要想实现函数对于对象的通用,我们的方法需要一个额外的参数来表示函数的接受者,这个参数通常被称为self或this:

function Account.withdraw ( self , v)

self.balance = self.balance – v

end

a1 = Account ; Account = nil

a1.withdraw(a1,100.00 )        

a2 = {balance=0, withdraw = Account.withdraw}

a2.withdraw ( a2,260.00 )

大多数面向对象语言都隐藏了self这个机制,从而使得程序员不必显式地声明这个参数。Lua语言同样可以使用冒号操作符(colon operator)隐藏该参数。使用冒号操作符,我们可以将上例重写为a2 : withdraw (260.00)。冒号的作用就是:定义函数时,给函数的添加隐藏的第一个参数self; 调用函数时,默认把当前调用者作为第一个参数传递进去。参见下段代码。

Account = { balance=0}

function Account : withdraw ( v)

self.balance = self.balance – v

end

function Account : deposit (v)

self.balance = self.balance + v

end

Account.deposit(Account,200.00 )

Account : withdraw( 100.00)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: