您当前的位置:首页 > 计算机 > 编程开发 > Lua

lua 中 __index 深入用法

时间:12-14来源:作者:点击数:

__index

访问 table 中的元素,不存在的时候,寻找 __index

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
w = Window.new{x = 10 ,y = 20}
print(w.wangbin)

__newindex

设置 table 中的元素,不存在的时候,进行赋值

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}
w.wangbin = "55"
print(w.wangbin)

rawget

为了绕过 __index

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))
打印结果是:nil。这里的元表中__index函数就不再起作用了

rawset

为了绕过 __newindex

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"

然后我们的程序就 stack overflow 了。可见,程序陷入了死循环。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐