1.新建一个文件,命名为Class.lua
2.Class.lua内容
--[[
模拟C++ 类实现
]]
function class(classname, super)
local superType = type(super)
local cls = {};
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- from native C++ Object
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.super = super
else
cls.__create = super
end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...);
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance:ctor(...)
return instance
end
else
-- from Lua Object
if super then
cls.super = super;
setmetatable(cls, super)
super.__index = super;
end
cls.__cname = classname
cls.__ctype = 2 -- lua
function cls.new(...)
local instance = {};
setmetatable(instance, cls)
cls.__index = cls;
instance:ctor(...)
return instance;
end
end
return cls
end
return class;
3.将文件require "Class" 到需要用的lua文件
2.Class.lua内容
--[[
模拟C++ 类实现
]]
function class(classname, super)
local superType = type(super)
local cls = {};
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- from native C++ Object
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.super = super
else
cls.__create = super
end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...);
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance:ctor(...)
return instance
end
else
-- from Lua Object
if super then
cls.super = super;
setmetatable(cls, super)
super.__index = super;
end
cls.__cname = classname
cls.__ctype = 2 -- lua
function cls.new(...)
local instance = {};
setmetatable(instance, cls)
cls.__index = cls;
instance:ctor(...)
return instance;
end
end
return cls
end
return class;
3.将文件require "Class" 到需要用的lua文件