1. 程式人生 > >lua中class的一種實現方式,單例擴充

lua中class的一種實現方式,單例擴充

方式 tab 方法 span 實用 ble 核心 攔截 說我

先上代碼

 1 local _class={}
 2  
 3 function class(super,singleton)
 4     local class_type={}
 5     class_type.ctor=false
 6     class_type.super=super
 7     class_type.new=function(...) 
 8             local obj={}
 9             do
10                 local create
11                 create = function
(c,...) 12 if c.super then 13 create(c.super,...) 14 end 15 if c.ctor then 16 c.ctor(obj,...) 17 end 18 end 19 20 create(class_type,...)
21 end 22 setmetatable(obj,{ __index=_class[class_type] }) 23 return obj 24 end 25 if singleton then 26 class_type.instance = singleton 27 class_type.Instance = function() 28 if class_type.instance==true then 29
class_type.instance = class_type.new() 30 end 31 return class_type.instance 32 end 33 end 34 local vtbl={} 35 _class[class_type]=vtbl 36 37 setmetatable(class_type,{__newindex= 38 function(t,k,v) 39 vtbl[k]=v 40 end 41 }) 42 43 if super then 44 setmetatable(vtbl,{__index= 45 function(t,k) 46 local ret=_class[super][k] 47 vtbl[k]=ret 48 return ret 49 end 50 }) 51 end 52 53 return class_type 54 end

想在lua項目中添加單例, class的核心部分是借鑒的雲風大神的代碼,由於實用了newindex元方法對類的賦值進行攔截並將vtbl方法集保存到_class中。所以沒法像之前習慣的方式添加class.Instance對類添加方法。所以在class中通過提前定義Instance的方式添加了單例的支持(類似於提前定義的ctor)

添加的過程中仔細看了下這個class這段代碼感覺寫的真是漂亮。先挖個坑,醞釀回味一下再繼續說說我對這個class的理解

lua中class的一種實現方式,單例擴充