编写lua代码时全用函数非常不好管理项目,在网上找到的一个C++风格的封装类,mark一下。 首先是baseClass:
local function parseName(str)
local _begin, _end, cls = assert(str:find('%s*([a-zA-Z][a-zA-Z0-9_]*)%s*%:?'))
if not str:find(':', _end) then
return cls, {}
end
local bases = {}
while true do
local base
_begin, _end, base = str:find('%s*([a-zA-Z][a-zA-Z0-9_]*)%s*%,?', _end + 1)
if base then
table.insert(bases, base)
else
break
end
end
return cls, bases
end
local function create(t, ...)
local o = {}
if t.__init__ then
t.__init__(o, ...)
end
return setmetatable(o, {__index = t, __class__ = t})
end
function class(name)
local env = getfenv(2)
local clsName, bases = parseName(name)
for i, v in ipairs(bases) do
bases[i] = env[v] --Replace string name with class table
end
return function (t)
local meta = {__call = create, __bases__ = bases}
meta.__index = function(nouse, key)
for _, cls in ipairs(meta.__bases__) do
local val = cls[key] --Do a recursive search on each cls
if val ~= nil then
return val
end
end
end
-- t.class = t --指向类,可以用于添加类成员
t.className = clsName --类名string
-- t.super = bases[1] --多重继承的第一个父类
env[clsName] = setmetatable(t, meta)
end
end
使用方法:
-- c++风格创建
class 'Person' --define a Class
{
__init__ = function(self, name) --define an instance initializer
self.name = name
end,
say = function(self) --define a method
if self.super then
print("className: ", self.className, "super: ", self.super.className)
else
print("className: ", self.className)
end
print('Hello, my name is ' .. (self.name or "no name") .. '.')
self:saySthElse()
end,
saySthElse = function(self)
end
}
class 'Employee: Person' --define a class inheriting class Person defined as above
{
__init__ = function(self, name, salary)
Person.__init__(self, name) --call base class's method directly
self.salary = salary
end;
saySthElse = function(self) --override base class's method
print('My salary is ' .. (self.salary or "no salary") .. '.')
end
}
每一个方法之间需要用逗号隔开,因为这些函数都属于table的一个元素。