前言:理解Lua语言中的__index, __newindex, rawget和 rawset在谈及Lua中的__index, __newindex, rawget和rawset前,需要理解Lua中的元表这个概念。
Window = {} Window.prototype = { x = 0 , y = 0 , width = 100 , height = 100, } Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = Window.prototype Window.mt.__newindex = function (table ,key ,value) if key == "wangbin" then rawset(table ,"wangbin" ,"yes,i am") end end 下面是测试: local w = Window.new{x = 10 ,y = 20} w.wangbin = "55" print(w.wangbin)
Window = {} Window.prototype = { x = 0 , y = 0 , width = 100 , height = 100, } Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = function (t ,key) -- body return 1000 end local w = Window.new{x = 10 ,y = 20} print(w.wangbin)
Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = function (t ,key) return 1000 end Window.mt.__newindex = function (table ,key ,value) if key == "wangbin" then rawset(table ,"wangbin" ,"yes,i am") end end 下面是测试 local w = Window.new{x = 10 ,y = 20} w.wangbin = "55" print(w.wangbin)
ok,这里的打印结果是:yes,i am。w这个表里本来没有wangbin这个元素的,我们重写了元表中__newindex,并在__newindex方法中重新进行赋值操作,然后,我们对这个本不存在的原色w.wangbin进行赋值时,执行__newindex方法的赋值操作,最后,打印结果便是:yes,i am
Window = {} Window.prototype = { x = 0 , y = 0 , width = 100 , height = 100, } Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = function (t ,key) return 1000 end Window.mt.__newindex = function (table ,key ,value) if key == "wangbin" then rawset(table ,"wangbin" ,"yes,i am") end end w = Window.new{x = 10 ,y = 20} print(rawget(w ,w.wangbin))
Window = {} Window.prototype = { x = 0 , y = 0 , width = 100 , height = 100, } Window.mt = {} function Window.new(o) setmetatable(o ,Window.mt) return o end Window.mt.__index = function (t ,key) return 1000 end Window.mt.__newindex = function (table ,key ,value) table.key = "yes,i am" end w = Window.new{x = 10 ,y = 20} w.wangbin = "55"
版权声明:本文为博主原创文章,未经博主允许不得转载。
跟我一起了解Lua语言中的_index,newindex,rawget和rawset
原文地址:http://blog.csdn.net/zwc2xm/article/details/47252969