
编写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,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,basesendlocal function create(t,...) local o = {} if t.__init__ then t.__init__(o,...) end return setMetatable(o,{__index = t,__class__ = t})endfunction 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) endend 使用方法:
-- 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的一个元素。 总结 以上是内存溢出为你收集整理的lua 封装成C++风格的类全部内容,希望文章能够帮你解决lua 封装成C++风格的类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)