Lua 之 面向对象 -- 继承

来源:互联网 发布:大数据金融 编辑:程序博客网 时间:2024/05/15 03:01

面向对象编程(Object Oriented Programming,OOP)是一种非常流行的计算机编程架构。
Lua的也是一种面向对象的语言,我们常见的面向对象的编程语言有:

C++JavaObjective-CSmalltalkC#Ruby面向对象具有三大特征:封装、继承、多态对象由属性和方法组成。LUA中最基本的结构是table,所以需要用table来描述对象的属性。

lua中的function可以用来表示方法。那么LUA中的类可以通过table + function模拟出来。
至于继承,可以通过metetable模拟出来(不推荐用,只模拟最基本的对象大部分时间够用了)

-- 继承Shape = {area = 0}-- 基础类方法 newfunction Shape:new (o,side)  o = o or {}  setmetatable(o, self)  self.__index = self  side = side or 0  self.area = side*side;  return oend-- 基础类方法 printAreafunction Shape:printArea ()  print("面积为 ",self.area)end--Square 继承自ShapeSquare = Shape:new()-- Shape自己的构造方法function Square:new (o,side)  o = o or Shape:new(o,side)  setmetatable(o, self)  self.__index = self  return oend--Rectangle 继承自ShapeRectangle = Shape:new()-- Rectangle 自己的构造方法function Rectangle:new (o,length,breadth)  o = o or Shape:new(o,side)  setmetatable(o, self)  self.__index = self  self.length = length or 0  self.breadth = breadth or 0  self.area = length*breadth;  return oendmyRectangle = Rectangle:new(nil,20,30)myRectangle:printArea()
0 0