LUA面向對象編程技巧


詳文請見 http://ffown.sinaapp.com/?p=11

1. LUA中的對象

我們知道,對象由屬性和方法組成。LUA中最基本的結構是table,So 必須用table描述對象的屬性。lua中的function可以用來表示方法。那么LUA中的類

可以通過table + function模擬出來。至於繼承,可以通過metetable模擬出來(不推薦用,只模擬最基本的對象大部分時間夠用了)。

2. Metatable

Lua中的metatable 類似於C++中的虛函數,當索引table中的項不存在時,會進一步索引metetable(如果設置了的話)是否存在該項。這跟虛函數概念

不是很吻合么?

3. 示例class

user_t = {}

user_t.__index = user_t

以上代碼聲明class user_t。為了方便,user_t聲明為全局的table。__index 是跟設置metatable有關,詳細信息參見lua manual http://www.lua.org/manual/5.1/

實際上__index 應該賦值為function,這里是一個語法糖,等價於

user_t.__index = function(key) return user_t[key] end 

定義構造函數:

function user_t:new(uid_)
local obj =
{
["uid"] = uid_,
}
setmetatable(obj, self)
return obj
end
function user_t:dump()
 print("self:", self.uid)
end

定義一個user_t對象代碼如下:

local user = user_t:new(1122334)

user:dump()

new 函數返回一個table, 當索引dump時,obj中沒有dump函數,嘗試去metatable中索引,獲得dump函數。

注意:

function user_t.dump(self) :方式定義函數只是個語法糖而已,其等價於
function user_t.dump(self)
print("self:", self.uid)
end


通常我都會對應定義一個析構函數(不好意思C++流)

function user_t:delete()
self.uid = nil
end

4. 實現繼承

原理就是利用metatable,__index 設置這樣的function,當前類不存在某項時,嘗試去基類中查出

person_t = {}
person_t.__index = person_t

function person_t:new()
local obj =
{
["type"] = "person",
}
setmetable(person_t, self)
return obj
end

function person_t:type()
print("type:", self["type"])
end

function user_t:new(uid_)
local obj =
{
["uid"] = uid_,
}
local mt =
{
["__index"] = function(key_)
local ret = user_t[key_] or person_t[key_]
return ret
end
}
setmetatable(obj, mt)
return obj
end
local user = user_t:new(1122334)
user:type()

5. 注意

1. 盡量不要使用多重繼承

2. 不要嘗試使用重載

 更多精彩文章 http://h2cloud.org

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM