LUA——元表


print("-------------------------__index方法--------------------------")
mytable = setmetatable({key1 = "value1"},{
__index = function(mytable,key)
	if key == "key2" then
		return "metatablevalue"
	else
		return nil
	end
end
})
print(mytable.key1,mytable.key2)

print("\n----------------------------__newindex方法------------------------")
mymetatable = {}
mytable = setmetatable({key1 = "value1"},{__newindex = mymetatable })

print(mytable.key1)

mytable.newkey = "新值1"
print(mytable.newkey,mymetatable.newkey)

mytable.key1 = "新值2"
print(mytable.key1,mymetatable.key1)


print("\n-------------------------rawset-------------------------------")
mytable = setmetatable({key1 = "value1"},{
 __newindex = function(mytable,key,value)
		rawset(mytable,key,value)
 end
})
mytable.key1 = "new value"
mytable.key2 = 4
print(mytable.key1,mytable.key2)

print("\n----------------------------添加操作符-----------------------")
function table_max(t)
	local temp_val = 0
	for k , v in pairs(t) 	do 
		if temp_val < k then
			temp_val = k
		end
	end
	return temp_val
end

mytable = setmetatable({3,5,6},{
 __add = function(mytable,newtable)
	for i=1 , table_max(newtable) do
		table.insert(mytable,table_max(mytable)+1,newtable[i]) 
	end
	return mytable
end
})

secondtable = {7,8,9}
mytable = mytable + secondtable
for k,v in ipairs(mytable) do
print(k,v)
end

print("\n-------------------__call元方法-----------------------------------")
--定义元方法__call
mytable = setmetatable({10},{
 __call = function(mytable,newtable)
	sum = 0
	for i = 1, table_max(mytable) do
		sum = sum + mytable[i]
	end
	for i = 1, table_max(newtable) do
		sum = sum + newtable[i]
	end
	return sum
end
})
newtable = {10,15,15}
print(mytable(newtable))

print("\n-------------------__tostring元方法---------------------------------")
mytable = setmetatable({10,20,20},{
__tostring = function(mytable)
	sum = 0
	for k , v in pairs(mytable) do
		sum = sum + v
	end
	return "表中所有元素的和为" .. sum
end
})
print(mytable)

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值