首页 > 代码库 > 面向对象

面向对象

__index的应用

Window_Prototype = {x=0, y=0, width=100, height=100, m ={i=50}}

Window_Prototype2 = {p=50, s=70}

MyWin = {title="Hello"}

setmetatable(MyWin, {__index = Window_Prototype})
setmetatable(MyWin, {__index = Window_Prototype2})
print(MyWin.x, MyWin.y, MyWin.width, MyWin.height, MyWin.p, MyWin.s, Window_Prototype.m.i)

注:__index 可以为表绑定其他成员并通过点的方式进行访问 MyWin.m.i 为错误访问形式(不明白为什么,继续学习)

 

 

继承的实现

Student = Person:new()
  
function Student:new()
    newObj = {year = 2013}
    self.__index = self
    return setmetatable(newObj, self)
end
  
function Student:toString()
    return "Student : ".. self.year.." : " .. self.name 
end

Student  继承自 Person

student new方法先执行父类的person的new然后对year重设

参考:http://coolshell.cn/articles/10739.html

面向对象