青海建设协会网站,wordpress怎么设置后台权限,昆明网站建设哪家便宜,上海最出名的编程培训详文请见 http://ffown.sinaapp.com/?p11 1. LUA中的对象 我们知道#xff0c;对象由属性和方法组成。LUA中最基本的结构是table#xff0c;So 必须用table描述对象的属性。lua中的function可以用来表示方法。那么LUA中的类 可以通过table function模拟出来。至于继承…详文请见 http://ffown.sinaapp.com/?p11 1. LUA中的对象 我们知道对象由属性和方法组成。LUA中最基本的结构是tableSo 必须用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 objend 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 nilend 4. 实现继承 原理就是利用metatable__index 设置这样的function当前类不存在某项时尝试去基类中查出 person_t {}
person_t.__index person_tfunction person_t:new()local obj
{
[type] person,
}
setmetable(person_t, self)return objendfunction person_t:type()print(type:, self[type])endfunction user_t:new(uid_)local obj
{
[uid] uid_,
}local mt
{
[__index] function(key_)local ret user_t[key_] or person_t[key_]return retend
}setmetatable(obj, mt)return objendlocal user user_t:new(1122334)
user:type() 5. 注意 1. 尽量不要使用多重继承 2. 不要尝试使用重载 更多精彩文章 http://h2cloud.org 转载于:https://www.cnblogs.com/zhiranok/archive/2012/02/07/lua_object_skill.html