Lua编程(二) 表面向对象、metatable对表进行扩展

 
counter = {
	count = 0
}
function counter.get(self)
	return self.count
end

function counter:inc()
	self.count=self.count+1
end

print(counter.get(counter))
counter.inc(counter)
print(counter.get(counter))

counter2={
	count=4,
	get = counter.get,
	inc = counter.inc,
}

print(counter2:get())
counter.inc(counter2)
print(counter2.get(counter2))

print()

tb1 ={ "alpha","beta","gamma"}
mt={}
setmetatable(tb1,mt)

print(getmetatable(tb1) == mt)

print()

function mt.__add(a,b)
	local result = setmetatable({},mt)
	for i=1,#a do
		table.insert(result,a[i])
	end
	for i=1,#b do
		table.insert(result,b[i])
	end
	return result
end

tb2={"aaa","bbb","ccc"}
res=tb1+tb2
for i,v in ipairs(res) do
	print(v)
end
print()
function mt.__unm(a)
	local result = setmetatable({},mt)
	for i=#a , 1 ,-1 do
		table.insert(result,a[i])
	end
	return result
end

res=-tb1+tb2
for i,v in ipairs(res) do
	print(v)
end

print()
function mt.__tostring(a)
	local result = "{"
	for i,v in ipairs(a) do
		result = result.." "..v
	end
	result = result.." } "
	return result
end

print(tb1)

function mt.__index(tb1,key)
	print("there is no "..key.." in the table")
	return nil
end

print(tb1["fsy"])

function mt.__newindex(a,key,v)
	if( key == "haha") then
		error(" Stop laugh!",2)
	else
		rawset(a,key,v)
	end
end

tb1.haha="heihei"


运行结果:

 

0
1
4
5

true

alpha
beta
gamma
aaa
bbb
ccc

gamma
beta
alpha
aaa
bbb
ccc

{ alpha beta gamma } 
there is no fsy in the table
nil
lua: my_test.lua:166:  Stop laugh!
stack traceback:
	[C]: in function 'error'
	my_test.lua:160: in function <my_test.lua:158>
	my_test.lua:166: in main chunk
	[C]: ?


  本篇博客出自  阿修罗道,转载请注明出处:http://blog.csdn.net/fansongy/article/details/7005166

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值