微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

lua 之__index/__newindex的理解

--example:
local temp_table ={
	10,1,Index1 = "hello",Index2 = "world",Index3 = "lua",Index4 = "language",lang = "lua language",}

temp_table.__add = function(a,b) return 3 end


for _,Value in pairs(temp_table) do
	print(Value)
end

local temp_Metable_table = {
	Index1 = "temp_new_Metable_Index1",Index2 = "temp_new_Metable_Index2",Key = "temp_new_Metable_Key_end",}


for _,Metable_Value in pairs(temp_Metable_table) do
	print(Metable_Value)
end
--只能访问temp_table的方法
--setMetatable(temp_Metable_table,temp_table) --如果setMetable 为这种方式的话,那么我不能够对Metable进行原子操作
--print(temp_Metable_table + temp_table)

--如果是这种方式的话,我们只能访问它的原子,也就是它的数据成员
--[[setMetatable(temp_Metable_table,{__index = temp_table} ) 

print(temp_Metable_table[1])
print(temp_Metable_table["lang"])--]]

--如果是__newindex的话,我们可以访问原table,找到相关的key,除此之外,你还可以自己给原table添加数据成员
setMetatable(temp_Metable_table,{__newindex = temp_table} ) 
temp_Metable_table[5] = 100
print(temp_Metable_table[5])
print(temp_table[5])



Window = {}

Window.prototype = {x = 0,y = 0,width = 100,height = 100,}
Window.mt = {}
function Window.new(o)
	setMetatable(o,Window.mt)
	print(getMetatable(o))
	print(getMetatable(Window.mt))
	return o
end

Window.mt.__index = function (t,key) //由于__index 给赋予了funcion,一个匿名函数
	-- body
	return 1000
end

w = Window.new({x = 10,y = 20})
print(w.a) //在这里虽然没有a这个成员,但是会认a为__index所绑定的function返回值作为a的值

Window = {}
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)

总结:

如果在元table中去找相应的操作,例如__index,__newindex等,如果有则直接访问,如果没有就新添加进元table中

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐