熟練使用Lua(四)面向物件:基於table的面向物件實現(2)
阿新 • • 發佈:2018-11-03
myluaootest.lua
–1. 基本原理
local Cal = {}
function Cal:New(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Cal:Add(a, b)
print("Cal Add")
return a + b
end
local SubCal = Cal:New()
function SubCal:Add(a, b)
print("SubCal Add")
return a + b + 10
end
–2. 雲風大大的優雅實現
https://blog.codingnow.com/cloud/LuaOO
local _class = {} local 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(x) print("A ctor", x) self.x = x end function A:print_x() print("A print_x", self.x) end function A:hello() print("A hello base_type") end local B = class(A) function B:ctor(x) print("B ctor", x) self.x = x + 1 end function B:hello() print("B hello base_type") end
local test = {} function test:main() --1 local a = SubCal:New() print(a:Add(1, 2)) --2 local a = A.new(1) a:print_x() a:hello() local b = B.new(10) b:print_x() b:hello() end return test --[[ 輸出結果 SubCal Add 13 A ctor 1 A print_x 1 A hello base_type A ctor 10 B ctor 10 A print_x 11 B hello base_type ]]