免费CHAT GPT-http://chat.winvvv.com欢迎使用

Lua编程示例(二):面向对象、metatable对表进行扩展城管执法车无牌上路丽江玉龙雪山

作者:网友 发布时间:2023-06-03 热度:1049℃



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= "
 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"

丽江玉龙雪山波音CEO谈C919

Random Image 毕棚沟风景区