Lua middleclass(v4.1) 解析

A simple OOP library for Lua. It has inheritance, metamethods (operators), class variables and weak mixin support.
https://github.com/kikito/middleclass

函数功能解析

1. _createClasss(aClass, super)

返回默认的表

  local dict = {}
  dict.__index = dict

  local aClass = { name = name, super = super, static = {},
                   __instanceDict = dict, __declaredMethods = {},
                   subclasses = setmetatable({}, {__mode='k'})  }

创建一个table,包含下列属性:
* name 类名
* super 父类的table
* static 静态表
* __instanceDict 存放类定义的属性和函数(包含父类)
* __decaredMethod (当前类声明的方法,不包含父类)
* subclasses 子类表, 使用弱引用

 if super then
    setmetatable(aClass.static, { __index = function(_,k) return rawget(dict,k) or super.static[k] end })
  else
    setmetatable(aClass.static, { __index = function(_,k) return rawget(dict,k) end })
  end

设置static表的元表为 __index = __instanceDict(或者super.static)

 setmetatable(aClass, { __index = aClass.static, __tostring = _tostring, 
 __call = _call, __newindex = _declareInstanceMethod }) 

设置类的元表:__index 为 static, __tostring => 默认tostring,
_call =>调用static.new(), __newindex => _declareInstanceMethod

2. _includeMixin(aClass, mixin)

将一张表合并到另一张表中

  for name,method in pairs(mixin) do
    if name ~= "included" and name ~= "static" then aClass[name] = method end
  end
  • 除了”included”和”static”,将mixin中的域全部赋值到aClass中(覆盖)
  for name,method in pairs(mixin.static or {}) do
    aClass.static[name] = method
  end
  • 将m
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值