1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| local function search(classes, key) for i = 1, #classes do local value = classes[i][key]; if value ~= nil then return value; end end end
local function (fun,...) local class_type={} class_type.ctor=false local parents = {...} if #parents > 0 then class_type.super=parents else class_type.super=nil end class_type.fun = fun class_type.new=function(...) local obj if class_type.fun then obj = class_type.fun(...) else obj = {} end do local create create = function(c,...) if c.super then for i = 1, #c.super do create(c.super[i],...) end end if c.ctor then c.ctor(obj,...) end end
create(class_type,...) end setmetatable(obj,{ __index=class_type }) return obj end
if class_type.super then setmetatable(class_type,{__index= function(t,k) local ret=search(class_type.super,k) class_type[k]=ret return ret end }) end
return class_type end
local base_type=class()
function base_type:ctor(x) print("base_type ctor") self.x=x end
function base_type:print_x() print("print base_type") print(self.x) self:print_b() end
function base_type:hello() print("hello base_type") end
local base_typeB=class() function base_typeB:ctor(x) print("base_typeB ctor") end
function base_typeB:print_b() print("print base_typeB") print(self.x) end
function base_typeB:helloB() print("hello base_typeB") end
local test=class(function() print("fun") return {} end, base_typeB,base_type)
function test:ctor() print("test ctor") end
function test:hello() print("hello test") end
local a=test.new(1) a:print_x() a:hello() a:helloB()
|