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
cls = {}
if superType == "table" then
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(...)
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
if super then
cls = {}
setmetatable(cls, {__index = super})
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
local ItemSystem = class("ItemSystem")
function ItemSystem:ctor()
print("ItemSys ctor")
end
function ItemSystem:add_item(x)
print("ItemSys add_item", x)
end
function ItemSystem:check_item()
print("ItemSys check_item")
end
function ItemSystem:del_item()
print("ItemSys del_item")
end
local User = class("User")
function User:ctor(game_server, account_id)
self.game_server = game_server
self.account_id = account_id
end
function User:is_init()
if not self.game_server then
print("model is not init, lack of game server")
return false
end
if not self.account_id then
print("model is not init, lack of account id")
return false
end
if not self.user_id then
print("model is not init, lack of user id")
return false
end
return true
end
function User:set_system(name, instance)
self[name.."_system"] = instance
for instance_k, instance_v in pairs(instance.class) do
if type(instance_v) == 'function' and instance_k ~= 'new' and instance_k ~= 'ctor' then
instance[instance_k] = function(...)
if not self:is_init() then
return
end
instance_v(instance, ...)
end
end
end
end
local user = User.new(1, 2)
user:set_system("item", ItemSystem.new(user))
user.item_system:add_item(10)