Please enable Javascript to view the contents

lua面向对象实现

 ·  ☕ 1 分钟  ·  ✍️ YSL

___index 当子表中,找不到某一个属性时候,会到元表中__index指定的表中去找索引

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- 封装
Class = {}
Class.__index = Class

function Class:new(...)
    local obj = {}
    setmetatable(obj,self)
    local ctor = self.ctor
	if ctor then
		ctor(obj,...)    --调用初始化函数
	end
    return obj
end
-- 继承
function LuaClass(BaseClass)
    local base = BaseClass or Class
    local cls = {}
    setmetatable(cls,base)
    cls.base = base
    cls.__index = cls
    return cls
end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
-- 使用
GameObject = LuaClass()
GameObject.posX = 0
GameObject.posY = 0

function GameObject:Move()
    self.posX = self.posX + 1
    self.posY = self.posY + 1
end
function GameObject:Print()
    print(2)
end
Player = LuaClass(GameObject)
local p1 = Player:new()
function p1:Move()
    self.posX = self.posX + 3
    self.posY = self.posY + 3
end
print(p1.posX)
p1:Move()
print(p1.posX)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Class = {}

function Class:new(...)
    local obj = {}
    setmetatable(obj,self)
    self.__index = self
    if(self.ctor) then
        self.ctor(obj,...)
    end
    return obj
end

-- 继承
function Class:subClass()
    local obj = {}
    obj.base = self
    self.__index = self
    setmetatable(obj,self)
    return obj
end
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- 使用
GameObject = Class:new()
GameObject.posX = 0
GameObject.posY = 0

function GameObject:Move()
    self.posX = self.posX + 1
    self.posY = self.posY + 1
end
function GameObject:Print()
    print(2)
end
Player = GameObject:subClass()
local p1 = Player:new()
function p1:Move()
    self.posX = self.posX + 3
    self.posY = self.posY + 3
end
-- print(p1.Hello(p1))
print(p1.posX)
p1:Move()
print(p1.posX)