加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua 之__index/__newindex的理解

发布时间:2020-12-14 22:14:20 所属栏目:大数据 来源:网络整理
导读:--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 endfor _,Value in pairs(temp_table) doprint(Value)endlocal temp_metable
--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中

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读