Lua系统学习17-面向对象OOP|类成员|类函数

逗号定义函数

Lua中类对象都是用table表示,因为lua是动态弱语言类型,table允许接收任意类型的元素,包括函数,所以table可以构成类的结构。

Account = {age = 0}
function Account.SetAge (v)
    Account.age = v
end

这个定义创建了一个名为SetAge新的函数,并且保存在Account对象里。Account.SetAge(11)

lua还提供一种函数定义和调用写法。

冒号定义函数

Account = {age = 0} 
function Account:SetAge (v) 
      self.age = v 
end

两者区别在于冒号定义方法,默认会接受self参数;而点号定义的时候,默认不会接受self参数;

实现继承特性

 

但是按照OOP的基本思想:封装、继承、多态三个特性,显然这样简单写法貌似继承这一特性就丢失了,而且类的概念也无了。如果需要更复杂的对象可以通过 metetable 模拟出继承。Lua系统学习16-Metetable元表 - 麦瑞克博客 (playcreator.cn)

- Meta class
Shape = {area = 0}
-- 基础类方法 new
function Shape:new (o,side)
  o = o or {}
  setmetatable(o, self)-- o代表当前“new的实例”,为o关联元表self。
  self.__index = self
  side = side or 0
  self.area = side*side;
  return o
end
-- 基础类方法 printArea
function Shape:printArea ()
  print("面积为 ",self.area)
end

-- 创建对象
myshape = Shape:new(nil,10)
--将Shape表认为类 myshape为Shape实例 内部setmetatable会为myshape提供的表(若不存在,创建一个然后返回,所以这个表就代表myshape)去设置Shape为它的元表
myshape:printArea()

Square = Shape:new()
-- 派生类方法 new
function Square:new (o,side)
  o = o or Shape:new(o,side)
  setmetatable(o, self)
  self.__index = self
  return o
end

-- 派生类方法 printArea
function Square:printArea ()
  print("正方形面积为 ",self.area)
end

-- 创建对象
mysquare = Square:new(nil,10)
mysquare:printArea()

Rectangle = Shape:new()
-- 派生类方法 new
function Rectangle:new (o,length,breadth)
  o = o or Shape:new(o)
  setmetatable(o, self)
  self.__index = self
  self.area = length * breadth
  return o
end

-- 派生类方法 printArea
function Rectangle:printArea ()
  print("矩形面积为 ",self.area)
end

-- 创建对象
myrectangle = Rectangle:new(nil,10,20)
myrectangle:printArea()

 

简单的说上面的示例就是将Shape、Square、Rectangle表认为类 myshape为Shape实例 内部setmetatable会为myshape提供的表(若不存在,创建一个然后返回,所以这个表就代表myshape)去设置Shape为它的元表并设置__index元方法以实现成员的继承,另外两个同理。

注意:Lua没有new操作符,示例所写的new都是自己定义的。包括Square = Shape:new() 只是忽略了实参,默认填入nil。实际调用的还是定义的function Shape:new (o,side) 方法

 

 

作者:Miracle
来源:麦瑞克博客
链接:https://www.playcreator.cn/archives/programming-life/lua/3470/
本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0许可协议,转载请注明!
THE END
分享
海报
Lua系统学习17-面向对象OOP|类成员|类函数
逗号定义函数 Lua中类对象都是用table表示,因为lua是动态弱语言类型,table允许接收任意类型的元素,包括函数,所以table可以构成类的结构。 Account = {age ……
<<上一篇
下一篇>>
文章目录
关闭
目 录