类
lua写类的时候成员变量和成员函数不能取名相同,不然会被覆盖找不到
查看成员函数是否存在可以 print(类.成员函数名)
Test_Class = {}
Test_Class.__index = Test_Class
function Test_Class:create()
local o = {}
setmetatable(o, self)
o.name = nil
o.age = nil
return o
end
function Test_Class:show()
print(self.name.." is "..self.age)
end
function Test_Class:setName(name)
self.name = name
end
function Test_Class:setAge(age)
self.age = age
end
test = Test_Class:create()
test:setName("Nr.Sila")
test:setAge(100)
test:show()
用lua进行面向对象的编程,声明方法和调用方法统一用冒号,对于属性的调用全部用点号
单继承
Animal = {}
function Animal:create()
local o = {}
setmetatable(o, self)
self.__index = self
o.name = nil
o.isCanFly = nil
return o
end
function Animal:show()
print(self.name.." is can fly: "..tostring(self.isCanFly))
end
function Animal:setName(name)
self.name = name
end
function Animal:setFly(isCanFly)
self.isCanFly = isCanFly
end
print("Base Class <Animal> begin-----")
test = Animal:create()
test:setName("Bird")
test:setFly(true)
test:show()
print("Base Class <Animal> end-----\n")
Human = {}
setmetatable(Human, Animal)
function Human:create()
local o = {}
setmetatable(o, self)
self.__index = self
o.isHighlyLevelLife = nil
return o
end
function Human:setHighlyLevelLife(isHighlyLevelLife)
self.isHighlyLevelLife = isHighlyLevelLife
end
function Human:show()
print(self.name.." is high level life: "..tostring(self.isHighlyLevelLife).." and can fly: "..tostring(self.isCanFly))
end
print("Derived Class <Human> begin-----")
human = Human:create()
human:setName("Nr.Sila")
human:setHighlyLevelLife(true)
human:setFly(false)
human:show()
print("Derived Class <Human> end-----")
单继承简单解释
father = {
house = 2,
}
son = {
car = 1,
}
father.__index = father --把father的__index方法指向自己
setmetatable(son, father) --son的元表为father
print(son.
house) --son不存在house查找元表father所指向的表方法.__index,即father.__index.house
Lua查找一个表元素时的规则
1.在表中查找,如果找到,返回该元素,找不到则继续
2.判断该表是否有元表,如果没有元表,返回nil,有元表则继续
3.判断元表有没有__index方法,如果__index方法为nil,则返回nil;
如果__index方法是一个表,则重复1、2、3;如果__index方法是一个函数,则返回该函数的返回值
middleclass实现