LUA面向对象编程技巧
詳文請見?http://ffown.sinaapp.com/?p=11
1. LUA中的對象
我們知道,對象由屬性和方法組成。LUA中最基本的結(jié)構(gòu)是table,So 必須用table描述對象的屬性。lua中的function可以用來表示方法。那么LUA中的類
可以通過table + function模擬出來。至于繼承,可以通過metetable模擬出來(不推薦用,只模擬最基本的對象大部分時間夠用了)。
2. Metatable
Lua中的metatable 類似于C++中的虛函數(shù),當(dāng)索引table中的項不存在時,會進一步索引metetable(如果設(shè)置了的話)是否存在該項。這跟虛函數(shù)概念
不是很吻合么?
3. 示例class
user_t = {}user_t.__index = user_t
以上代碼聲明class user_t。為了方便,user_t聲明為全局的table。__index 是跟設(shè)置metatable有關(guān),詳細信息參見lua manual?http://www.lua.org/manual/5.1/
實際上__index 應(yīng)該賦值為function,這里是一個語法糖,等價于
user_t.__index = function(key) return user_t[key] end定義構(gòu)造函數(shù):
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 函數(shù)返回一個table, 當(dāng)索引dump時,obj中沒有dump函數(shù),嘗試去metatable中索引,獲得dump函數(shù)。
注意:
function user_t.dump(self) :方式定義函數(shù)只是個語法糖而已,其等價于 function user_t.dump(self)print("self:", self.uid)
end
通常我都會對應(yīng)定義一個析構(gòu)函數(shù)(不好意思C++流)
self.uid = nil
end
4. 實現(xiàn)繼承
原理就是利用metatable,__index 設(shè)置這樣的function,當(dāng)前類不存在某項時,嘗試去基類中查出
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
?
轉(zhuǎn)載于:https://www.cnblogs.com/zhiranok/archive/2012/02/07/lua_object_skill.html
總結(jié)
以上是生活随笔為你收集整理的LUA面向对象编程技巧的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IBM软件OEM概览
- 下一篇: HDU3363_贪心