SpringDragon

导航

 

 

 

--对于一个对象来说,是有属性和方法的

person = {name = "chenquanlong",age=18};

--第一种
--[[
person.eat = function()
  print(person.name.."在吃饭")
end
--]]

--当使用:定义一个值的时候,我们可以在这个方法里面使用self

function person:eat()
  print(self.name.."在吃饭")
end
--person.eat(person)等价于person:eat()
--在使用面向对象的时候使用:来实现方法
--当通过:调用的时候,系统会自动传递当前table给self,当通过.来调用方法的时候,self不会自动赋值,我们必须通过第一个参数来传递当前的table

--构造
--lua无法像C#一样去定义一个对象,在lua里面我们可以先做一个原型,这个原型是不作为实际使用的
--作为整个table的原型,根据这个原型去创建新的表,即对象
Person = {name = "chenquanlong",age=18};
function Person :eat()
  print(self.name.."在吃饭")
end
--通过下面的方法去获得一个新表
function Person:new(tab)
  local t = tab or {};
  setmetatable(t,{__index = self})
  return t;
end

person1 = Person:new(nil);
person2 = Person:new(nil);
person1:eat();

--继承
--上面由person原型 ,person1和person2继承person
Student = Person:new();
student1=Student:new();
student1:eat();

  

posted on 2019-05-28 11:45  chenquanlong  阅读(177)  评论(0编辑  收藏  举报