lua table访问的元方法
2015-11-09 16:19
453 查看
1。__index元方法
Window = {} --创建一个名字空间
--使用默认值来创建一个原型
Window.prototype = {x=0,y=0,width=100,height=100}
Windwo.mt = {} --创建元表
--声明构造函数
function Window.new(o)
setmetatable(o,Window.mt)
return o
end
定义__index元方法:
Window.mt.__index = function(table,key)
return Window.prototype(key)
end
w = Window.new{x=10,y =20}
print(w.width) -->200
__index元方法不必一定是一个函数,也可以是一个table,
例如 Window.mt.__index = Window.prototype这个跟上面的函数是等效的
2.__newindex元方法
__newindex元方法与__index 类似,不同之处在于前者用于table的更新,而后者用于table的查询
3.具有默认值的table
function setDefault(t,d)
local mt = {__index = function() return d end}
setmetatable(t,mt)
end
tab = {x=10,y=20}
print(tab.x,tab.z) -->10,nil
print(tab.x,tab.z) -->10,0
但是这个方法不好,默认值d和元方法关联在一起了,无法为所有table都使用用一个元表,改进一下,把默认值存放在table本身中,用一个额外的字段保存
local mt = {__index = function(t) return t.___end}
function setDefault(t,d)
t.___ = d
setmetatable(t,mt)
end
4.跟踪table的访问
local index = {} --创建私有索引
local mt = {
__index = function(t,k)
print("* access to element "..tostring(k))
return t[index][k]
end
__newindex = function(t,k,v)
print("*update of element " ..tostring(k).."to"..tostring(v))
t[index][k] = v --更新原来的table
end
}
function track(t)
local proxy = {}
proxy[index] = t
setmetatable(proxy,mt)
return proxy
end
现在,若要监视table t,唯一要做的就是执行: t = track(t)
Window = {} --创建一个名字空间
--使用默认值来创建一个原型
Window.prototype = {x=0,y=0,width=100,height=100}
Windwo.mt = {} --创建元表
--声明构造函数
function Window.new(o)
setmetatable(o,Window.mt)
return o
end
定义__index元方法:
Window.mt.__index = function(table,key)
return Window.prototype(key)
end
w = Window.new{x=10,y =20}
print(w.width) -->200
__index元方法不必一定是一个函数,也可以是一个table,
例如 Window.mt.__index = Window.prototype这个跟上面的函数是等效的
2.__newindex元方法
__newindex元方法与__index 类似,不同之处在于前者用于table的更新,而后者用于table的查询
3.具有默认值的table
function setDefault(t,d)
local mt = {__index = function() return d end}
setmetatable(t,mt)
end
tab = {x=10,y=20}
print(tab.x,tab.z) -->10,nil
print(tab.x,tab.z) -->10,0
但是这个方法不好,默认值d和元方法关联在一起了,无法为所有table都使用用一个元表,改进一下,把默认值存放在table本身中,用一个额外的字段保存
local mt = {__index = function(t) return t.___end}
function setDefault(t,d)
t.___ = d
setmetatable(t,mt)
end
4.跟踪table的访问
local index = {} --创建私有索引
local mt = {
__index = function(t,k)
print("* access to element "..tostring(k))
return t[index][k]
end
__newindex = function(t,k,v)
print("*update of element " ..tostring(k).."to"..tostring(v))
t[index][k] = v --更新原来的table
end
}
function track(t)
local proxy = {}
proxy[index] = t
setmetatable(proxy,mt)
return proxy
end
现在,若要监视table t,唯一要做的就是执行: t = track(t)
相关文章推荐
- lua 算术类和关系类的元方法
- lua 模式匹配
- 1.lua
- LUA语言注意点归集
- [Lua]Lua语言基础汇总 -- 函数
- Python导出Excel为Lua/Json/Xml实例教程(一):初识Python
- Lua_Lua中的闭包小结
- Lua_Lua中的数学库总结
- lua和c的交互
- Luajit 2.0.4 绑定 protoc-gen-lua (Windows 平台)
- Eclipse中安装Lua Eclipse插件
- lua调用syslog; 使用C注册lua方法
- protoc-gen-lua 编译、安装、使用教程
- C调用Lua -- 简单的解释器程序实现
- Lua的面向对象封装
- lua 单例 and c++单例
- Lua模块测试
- Lua1.1 Lua 的参考手册 (三)
- Lua1.1 Lua 的参考手册 (二)
- Lua1.1 Lua 的参考手册 (一)