众所周知lua是没有类的概念
但是为了方便开发,可以使用table实现一个class
看了下lua pureMVC的class实现
因为是在工程中使用,写了很多关于安全的代码
其实跟class本身的特性无关
class的功能无非是:派生,继承
所以实现这两个就行了
另外安利一下VS code里的插件luaide
确实挺好用的,才一百块钱买断
function class(className,...)
local l_table = {name=className}
l_table.supers={...}
--继承实现
setmetatable(l_table,{__index=function(_,v)
local l_sp = l_table.supers
for i=1,#l_sp do
if l_sp[i][v] then
return l_sp[i][v]
end
end
end})
--派生实现
l_table.new = function(...)
local l_instance
l_instance = {}
inherit(l_instance,l_table)
return l_instance
end
return l_table
end
inherit=function(derived,super)
local l_mt = getmetatable(derived)
if not l_mt then
l_mt = {}
end
if not l_mt.__index then
l_mt.__index = super
setmetatable(derived,l_mt)
elseif l_mt.__index ~= super then
inherit(l_mt,super)
end
end