--表 元表 元方法结合起来可以实现lua面向对象的机制
--lua中通过原型的思路才使用实现对象的实例化机制
--一个原型表可以用来描述一个类 在原型表中填写属性和方法
--实例化对象,创建一个新表,将新表的元表设置为原型表.将原型表的__index指向自身
--类似js的面向对象机制
function Human(name)
local this={ name=name, a=1, b=2, c=3, d=4 }
this.eat=function(food)
print(this.name.." eats "..food)
end
this.add=function(n)
this.a,this.b,this.c,this.d=this.a+n,this.b+n,this.c+n,this.d+n
end
this.getName=function()
print("my name is "..this.name)
end
this.print=function()
print(this.a,this.b,this.c,this.d)
end
return this
end
a=Human("Hover")
b=Human("Lees")
a.eat("meat bun")
b.eat("sweet bun")
a.add(1)
b.add(2)
a.getName()
a.print()
b.getName()
b.print()
--[[
my name is Hover
2 3 4 5
my name is Lees
3 4 5 6
]]
--LUA中内置的面向对象的机制
Set={}
local mt={}
function Set.new(l)
local set={}
setmetatable(set,mt)--设置对象的元表 之后通过对元表的操作来使对象具有其他的操作行为
for _,v in ipairs(l) do
set[v]=true
end
return set
end
function Set.union(a,b)
local res=Set.new{}
for k in pairs(a) do
res[k]=true
end
for k in pairs(b) do
res[k]=true
end
return res
end
function Set.intersection(a,b)
local res=Set.new{}
for k in pairs(a) do
res[k]=b[k]
end
return res
end
function Set.tostring(set)
local l={}
for e in pairs(set) do
l[#l+1]=e
end
return "{"..table.concat(l,",").."}"
end
function Set.print(s)
print(Set.tostring(s))
end
s1=Set.new{10,20,30,40}
s2=Set.new{10,50}
print(Set.print(Set.union(s1,s2)))
结果为:{20,10,40,30,50}