加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua 封装成C++风格的类

发布时间:2020-12-14 22:15:21 所属栏目:大数据 来源:网络整理
导读:编写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 r

编写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,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的一个元素。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读