luckyyyyy / blog

William Chan's Blog
https://williamchan.me/
172 stars 28 forks source link

lua 中的 oo #40

Open luckyyyyy opened 4 years ago

luckyyyyy commented 4 years ago

很久没写lua了,最近在学习王争的设计模式之美,所以还是补一下功课。 非面向对象语言利用语言特性实现面向对象的部分特性。

local _class = {}

function class(super)
  local class_type = {}
  class_type.ctor = false
  class_type.super = super
  class_type.new = function(...)
    local obj = {}
    do
      local create
      create = function(c, ...)
        if c.super then
          create(c.super, ...)
        end
        if c.ctor then
          c.ctor(obj, ...)
        end
      end
      create(class_type, ...)
    end
    setmetatable(obj,{ __index=_class[class_type] })
    return obj
  end
  local vtbl = {}
  _class[class_type] = vtbl
  setmetatable(class_type, { __newindex = function(t, k, v)
      vtbl[k] = v
    end
  })

  if super then
    setmetatable(vtbl, { __index = function(t, k)
      local ret = _class[super][k]
      vtbl[k] = ret
      return ret
    end})
  end
  return class_type
end

local a = class()
function a:ctor()
  self.hello = 1;
    return self
end

function a:print()
    print(self.hello)
end

-- class
A = setmetatable({}, { __call = function(me, ...) return a:new( ... ) end, __metatable = true, __newindex = function() end })

local b = class(a)
function b:ctor()
  self.hello2 = 2;
    return self
end

function b:print2()
    print(self.hello2)
end

B = setmetatable({}, { __call = function(me, ...) return b:new( ... ) end, __metatable = true, __newindex = function() end })

local instance = B()
-- for k, v in pairs(instance) do
--   print(k)
-- end
instance:print()
instance:print2()