看了两天Lua,尝试用table模拟java的对象,用的Lua版本Lua 5.1.4;
Demo:
--父类Animal,子类Dog和Cat
Animal = {createSum = 0, showCreateSum = function() print("----animal createsum:"..Animal.createSum) end} --相当于static的
Animal.__index = Animal --为Constructor里的setmetatable(o, Animal)准备
Constructor = {
__call = function(obj, name)
Animal.createSum = Animal.createSum + 1 --记录创建Animal次数
local o = {}
setmetatable(o, Animal) --将o的元表设置为Animal,可以使用__index找Animal的属性
o.name = name or ""
return o
end}
setmetatable(Animal, Constructor) --为了使用Animal()调用Constructor的__call方法
function Animal:run()
print(self.name.." is running.")
end
--[[
function showAnimalCreateSum()
print("--animal createsum:"..Animal.createSum)
end
]]--
a = Animal("Tom")
--showAnimalCreateSum()
Animal.showCreateSum()
a:run()
Dog = {}
Dog.__index = Dog --为DogConstructor里的setmetatable(o, Dog)准备
DogConstructor = {
__index = Animal, --Dog找不到去找Animal
__call = function(dog, name, age)
local o = Animal(name) --设置了下name并与Animal里的名字一致
setmetatable(o, Dog) --将o的元表设置为Dog,元表不再是Animal
o.age = age --设置额外属性
return o
end
}
setmetatable(Dog, DogConstructor) --能够使用Dog(),Dog里找不到使用__index找到Animal里
d = Dog("DDDD", 11)
--showAnimalCreateSum()
Animal.showCreateSum()
d:run() --d的元表是Dog,Dog里找不到,通过__index找到Animal里的run
function Dog:run() --模拟重写run,其实是Dog方法
print([[Dog "]]..self.name..[[" is running......]])
end
d:run() --Dog元表里的run方法
Dog.__tostring = function(dog) return "dog name:"..dog.name..",age:"..dog.age end --Dog的tostring方法
print(d)
d2 = Dog("DD2", 10)
--showAnimalCreateSum()
Animal.showCreateSum()
d2:run()
print(d2)
Cat = {}
Cat.__index = Cat
CatConstructor = {
__index = Animal,
__call = function(cat, name, color)
local o = Animal(name)
setmetatable(o, Cat)
o.color = color
return o
end
}
setmetatable(Cat, CatConstructor)
function Cat:eat(food) --Cat自己的方法
print(self.color.." "..self.name.." eat "..food..".")
end
Cat.__tostring = function(cat) return "a "..cat.color.." cat named "..cat.name end
c = Cat("Kitty", "blue")
--showAnimalCreateSum()
Animal.showCreateSum()
c:run()
c:eat("fish")
print(c)
print(string.rep("*", 40))
a:run()
print("a=", a)
d:run()
print("d=", d)
d2:run()
print("d2=", d2)
c:run()
c:eat("goldfish")
print("c=", c)
--showAnimalCreateSum()
Animal.showCreateSum()
输出结果: