Lua程序员

Lua middleclass 详解

2016-08-08  本文已影响442人  chiguozi

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,包含下列属性:

 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
  for name,method in pairs(mixin.static or {}) do
    aClass.static[name] = method
  end
  if type(mixin.included)=="function" then mixin:included(aClass) end

3. DefaultMixin

** 默认合并表,创建类时自动添加到类中**
提供如下方法:

 isInstanceOf = function(self, aClass)
    return type(aClass) == 'table' and (aClass == self.class or self.class:isSubclassOf(aClass))
  end,

为static添加方法:

allocate = function(self)
      assert(type(self) == 'table', "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'")
      return setmetatable({ class = self }, self.__instanceDict)
    end,
new = function(self, ...)
      assert(type(self) == 'table', "Make sure that you are using 'Class:new' instead of 'Class.new'")
      local instance = self:allocate()
      instance:initialize(...)
      return instance
    end,
 subclass = function(self, name)
      assert(type(self) == 'table', "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'")
      assert(type(name) == "string", "You must provide a name(string) for your class")

      local subclass = _createClass(name, self)

      for methodName, f in pairs(self.__instanceDict) do
        _propagateInstanceMethod(subclass, methodName, f)
      end
      subclass.initialize = function(instance, ...) return self.initialize(instance, ...) end

      self.subclasses[subclass] = true
      self:subclassed(subclass)

      return subclass
    end,

 isSubclassOf = function(self, other)
      return type(other)      == 'table' and
             type(self.super) == 'table' and
             ( self.super == other or self.super:isSubclassOf(other) )
    end,
  include = function(self, ...)
      assert(type(self) == 'table', "Make sure you that you are using 'Class:include' instead of 'Class.include'")
      for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end
      return self
    end

4. _declareInstanceMethod(aClass, name, f)

在类中添加声明方法和属性

local function _declareInstanceMethod(aClass, name, f)
  aClass.__declaredMethods[name] = f

  if f == nil and aClass.super then
    f = aClass.super.__instanceDict[name]
  end

  _propagateInstanceMethod(aClass, name, f)
end

5. _propagateInstanceMethod(aClass, name, f)

添加域到表中,并添加到所有的子类中,相当于继承

local function _propagateInstanceMethod(aClass, name, f)
  f = name == "__index" and _createIndexWrapper(aClass, f) or f
  aClass.__instanceDict[name] = f

  for subclass in pairs(aClass.subclasses) do
    if rawget(subclass.__declaredMethods, name) == nil then
      _propagateInstanceMethod(subclass, name, f)
    end
  end
end

6. _createIndexWrapper(aClass, f)

对__index处理

local function _createIndexWrapper(aClass, f)
  if f == nil then
    return aClass.__instanceDict
  else
    return function(self, name)
      local value = aClass.__instanceDict[name]

      if value ~= nil then
        return value
      elseif type(f) == "function" then
        return (f(self, name))
      else
        return f[name]
      end
    end
  end
end

7. _call(self, ...)

调用new方法,使A:new() <==> A()

8. _tostring(self)

** 默认tostring方法**

9. middleclass.class(name, super)

创建一个类,并设置父类

实例解析

Metamethods

不需设置metatable的元方法,直接在当前类中定义,即可实现原方法。
以tostring为例:

Point = class('Point')
function Point:initialize(x,y)
  self.x = x
  self.y = y
end
function Point:__tostring()
  return 'Point: [' .. tostring(self.x) .. ', ' .. tostring(self.y) .. ']'
end

p1 = Point(100, 200)
p2 = Point(35, -10)
print(p1)
print(p2)

Output:
Point: [100, 200]
Point: [35, -10]

  1. p1(实例)的__index为__instanceDict,所以调用tostring时,会去__instanceDict中去查找
  2. Pointer的__newindex为_declareInstanceMethod,在类中定义__tostring时,_declareInstanceMethod会将该方法加入到__instanceDict中
  3. 重写__tostring,相当于在自己的元表中定义该方法
  4. 其他元方法类似

Middleclass 4.x supports all the Lua metamethods. There are some restrictions:

mixins

类变量提供include方法,可以将一个table的域拷贝到另一个table中,被拷贝的table会触发included方法

  1. class.static表中提供include方法
  2. class的__index指向class.static
  3. 被合并的table 调用include方法

Private stuff

在类内定义局部变量,或者局部函数,外部不可访问

lua的作用于限制

其他

class = require("middleclass")
A = class("A")
A.n = 1
B = A()
print(B.n)
B.n = 2
print(B.n)
print(A.n)

Output:
1
2
1

B是A的实例,B继承了n(B中没有n属性,则去__instanceDict中取)
当B对n赋值,则相当于在B表中添加属性,不会改变__instanceDict的值,再次获取该属性时,直接从B表中读,所以值为2,且不会改变A中的值

middleclass使用的表的简单总结

  1. __instanceDict 记录当前类,以及所有父类定义的实例方法(属性), __index指向自己
  2. __declaredMethods 记录当前类声明的方法(属性)
  3. subclasses 当前类的所有子类,弱引用
  4. static 静态表,定义new, include, isSubclassOf等方法,__index指向__instanceDict。
    实例变量不能直接访问static表,必须通过.class.static访问
    类的静态方法可以通过class.static:func 来定义
  5. 类的默认表 定义__instanceDict,__declaredMethods, static等属性。
    __index指向static表,可以直接使用static中的字段(A:new())。
    __newIndex为_declareInstanceMethod方法,添加字段时会更新__instanceDict以及__declareMethods
  6. 实例表 定义class属性,指向当前的类。 metatable为对应类的__instanceDict
上一篇 下一篇

猜你喜欢

热点阅读