Lua 元表

例程
a = {1, 2, 3}
b = {2, 3, 4}

mt = {}
mt.__add = function(a,b)
	local len = table.getn(a);
	local res = {}
	for i = 1, len do
		res[i] = a[i] + b[i]
	end

	return res
end
setmetatable(a, mt)
setmetatable(b, mt)
c = a + b
for k, v in ipairs(c) do
	print(k, v)
end
运行结果
1 3
2 5
3 7


__add (+)
__sub (-)
__mul (*)
__div (/)
__mod (%)
__pow (^)
__unm 
__concat (..)
__len (#)
__eq (==)
__lt (<)
__le (<=)
__index  (table[key])
__newindex (table[key] = value)
__call 
__tostring (打印表中元素)

例程: __index

tab = {a = 5, b = 7}
tab.__index = function(t, key)
	return tab[key]
end

tab.__newindex = function(t, key, val)
	tab[key] = val
end

mytab = {}
setmetatable(mytab, tab)
print(mytab.a)	-- 元素不存在时,将访问元表
print(rawget(mytab, a))	-- 判断表 mytab 中是否存在 a

mytab.test = 9	-- 这个值被存入元表,调用了 __newindex
print(mytab.test)
print(rawget(mytab, test))
运行结果
5
nil
9

nil

例程

tab = {a = 5, b = 7}
tab.__index = function(t, key)
	return tab[key]
end

tab.__newindex = function(t, key, val)
	tab[key] = val
end

tab.__tostring = function(t)	-- 打印表 mytab 中的元素
	local l = table.getn(t)
	local s = ""
	for i = 1, l do
		s = s .. t[i] .. ","
	end

	return s
end

mytab = {2,3,4}
setmetatable(mytab, tab)
print(mytab.a)	-- 元素不存在时,将访问元表
print(rawget(mytab, a))	-- 判断表 mytab 中是否存在 a

mytab.test = 9	-- 这个值被存入元表,调用了 __newindex
print(mytab.test)
print(rawget(mytab, test))

print(mytab)
运行结果
5
nil
9
nil
2,3,4,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值