Lua 面向对象的原理
lua本身是没有类的。但lua有元表和元方法,通过元表和元方法我们可以实现类的一些特征。
father = {house = 1}
son = {car = 2}
function father:printHouse()
print("father house is ",self.house)
end
function father:printHello()
print("father hello")
end
function son:printHouse()
print("son house is ",self.house)
end
function test()
father:printHouse()
son:printHouse()
setmetatable(son,father)
father.__index = father
son:printHouse()
father.__newindex = father
son.house = 2
son:printHouse()
father:printHouse()
son:printHello()
father:printHello()
end
输出:
[LUA-print] father house is1
[LUA-print] son house is nil
[LUA-print] son house is 1
[LUA-print] son house is 2
[LUA-print] father house is 2
[LUA-print] father hello
[LUA-print] father hello
[LUA-print] son house is nil
[LUA-print] son house is 1
[LUA-print] son house is 2
[LUA-print] father house is 2
[LUA-print] father hello
[LUA-print] father hello
首先,son house is nil,son没有house这个变量,所以为nil。当father作为元表赋给son时,lua 的执行顺序变成如下:son中如果没有house->到元表__index中去找house.这就实现了子类读父类的属性。同理,son中的函数也是一样。
而赋值,执行顺序如下:son中如果没有house->到元表__newindex中去找house.这就实现了子类写父类的属性