lua 封装成C++风格的类

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值