面向对象编程是目前比较主流的做法,在lua中并没有类的概念,只有table,通过table的特性,我们可以自己构造一个类。
关于这方面的资料比较多,就不在说明,不清楚的可以直接百度,这里提供一个云风大神的连接
在 Lua 中实现面向对象
下面提供一个类的实现,仅供参考,不知道哪里来的了
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 == ) then
-- inherited from native C++ Object
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 =
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.class = cls
instance:ctor(...)
return instance
end
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 = -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
--TODO:2015 8 10
if app~=nil then
app.classDic[cls.__cname]=cls
end
return cls
end