此文 class 类是基于 Cocos2d-Lua 中的 class 类的实现,它为 Lua 提供了面向对象编程的支持。通过 class 类,我们可以定义一个 Lua 类,包含成员变量和成员函数,并且可以实现类的继承和构造函数等特性。此外,该 class 类的实现还支持多重继承、方法重载和元表等特性,为 Lua 编程提供了更加灵活和强大的功能。使用该 class 类,开发者可以更加方便地编写可维护、可扩展和易于调试的 Lua 代码,同时也有助于提高程序的运行效率和性能表现。
-- 创建一个类
-- @param string classname 类名
-- @param [mixed super] 父类或者创建对象实例的函数
function class(classname, super)
-- 判断父类的类型,只支持函数和表两种类型
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
-- 如果父类是函数类型或者父类是C#类型的对象,则创建Lua对象继承C#对象
if superType == "function" or (super and super.__ctype == 1) then
cls = {}
-- 如果父类是表类型,则将父类中的字段拷贝到子类中
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
-- 如果父类是函数类型,则创建一个空表,把父类作为创建对象实例的函数保存起来
cls.__create = super
cls.ctor = function() end
end
-- 设置类名、父类类型、创建对象实例的方法
cls.__cname = classname
cls.__ctype = 1
-- 定义创建对象实例的方法
function cls.new(...)
-- 调用父类的创建对象实例的方法创建一个对象
local instance = cls.__create(...)
-- 将子类中的字段拷贝到对象的peer表中
local peer = tolua.getpeer(instance)
if not peer then
peer = {}
tolua.setpeer(instance, peer)
end
for k,v in pairs(cls) do peer[k] = v end
-- 保存类信息到对象的peer表中
peer.class = cls
-- 调用构造函数初始化对象
instance:ctor(...)
return instance
end
-- 如果父类是表类型,则创建Lua对象继承Lua对象
else
-- inherited from Lua Object
-- 如果父类存在,则将子类的元表设置为父类
if super then
cls = {}
setmetatable(cls, {__index = super})
cls.super = super
else
-- 如果父类不存在,则创建一个空表,并定义一个空的构造函数
cls = {ctor = function() end}
end
-- 设置类名、父类类型、元表
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
-- 定义创建对象实例的方法
function cls.new(...)
-- 创建一个空对象
local instance = setmetatable({}, cls)
-- 在对象中保存类信息
instance.class = cls
-- 调用构造函数初始化对象
instance:ctor(...)
return instance
end
end
-- 返回创建好的类
return cls
end
示例
-- 定义父类 Person
local Person = class("Person")
function Person:ctor(name)
self.name = name
end
function Person:sayHello()
print("Hello, my name is " .. self.name)
end
-- 定义子类 Student,并继承 Person
local Student = class("Student", Person)
function Student:ctor(name, grade)
Student.super.ctor(self, name)
self.grade = grade
end
function Student:sayHello()
print("Hello, my name is " .. self.name .. ", and I'm in grade " .. self.grade)
end
-- 创建 Person 和 Student 的实例
local p = Person.new("Tom")
p:sayHello() -- 输出:Hello, my name is Tom
local s = Student.new("Jerry", 3)
s:sayHello() -- 输出:Hello, my name is Jerry, and I'm in grade 3