Lua语言学习-面向对象

菜鸟教程 https://www.runoob.com/lua/lua-object-oriented.html

面向对象特征
1) 封装:指能够把一个实体的信息、功能、响应都装入一个单独的对象中的特性。
2) 继承:继承的方法允许在不改动原程序的基础上对其进行扩充,这样使得原功能得以保存,而新功能也得以扩展。这有利于减少重复编码,提高软件的开发效率。
3) 多态:同一操作作用于不同的对象,可以有不同的解释,产生不同的执行结果。在运行时,可以通过指向基类的指针,来调用实现派生类中的方法。
4)抽象:抽象(Abstraction)是简化复杂的现实问题的途径,它可以为具体问题找到最恰当的类定义,并且可以在最恰当的继承级别解释问题。

对象 --> 属性+方法

 

lua中使用table + function来实现面向对象

-- Meta class
Shape = {area = 0}

pMate = {__index = Shape}
-- 基础类方法 new
function Shape:new (o,side)
  local o = o or {}
  -- 3种写法
 setmetatable(o, pMate)
    
  -- setmetatable(t, {__index = self})
  
  --setmetatable(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)

myshape:printArea()

 

实现了继承的示例

-- Meta class
Shape = {area = 0}
-- 基础类方法 new
function Shape:new (o,side)
  o = o or {}
  setmetatable(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)
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()

 

游戏中entity和player的使用示例

_G.entityBase = {}
function entityBase.new(  t )
    t = t or { }
    t.pos = _Vector3.new()
    t.sizeR = 5
    t.shadowR = 5
    
    t.isTransform = entityBase.isTransform

    return t
end
--是否变身中
function entityBase:isTransform()
end





_G.player = {}
local playerMeta = { __index = player }

function player.new( t )
    local p = t or {}
    p = entityBase.new( p )
    p.target = _Vector3.new( 0, 0, 0 )

    p.sca3D = _Matrix3D.new()
    p.rot3D = _Matrix3D.new()
    p.tran3D = _Matrix3D.new()

    p.sca3D.parent = p.rot3D
    p.rot3D.parent = p.tran3D    --xmzNote

    p.type = 'player'
    p.sex = MAN
    p.id = ''
    p.tfid = 0

    return setmetatable( p, playerMeta )
end
function player:isReLevel()--是否转生
end

function player:getRealmImage()
end

 

posted @ 2019-05-09 18:19  orxx  阅读(335)  评论(0编辑  收藏  举报