lua简单实现面向对象
--父类 local Person = { name = "XX" , age = 0 , PrintName = function(self) print("PersonName : "..self.name) end , new = function(self,name,age) obj = {} --创建并赋值实例的字段 obj.name = name obj.age = age setmetatable(obj , {__index = self}) return obj end , PrintAge = function(self) print(self.name.."age"..self.age); end } --子类 local Student = { PrintName = function(self) print("StudentName : "..self.name) end , new = function(self,name,age) obj = {} setmetatable(obj , {__index = self}) --创建并赋值实例的字段 obj.name = name; obj.age = age return obj end } setmetatable(Student , {__index = Person}) --Student.__newindex = Person local zhangsan = Student:new("zhangsan",20) local lisi = Person:new("lisi",25) zhangsan:PrintName() lisi:PrintName() --用的是父类的方法,但使用的数据是zhangsan的name和age(用self传过去的),字段无法实现继承,需要每个实例都创建 zhangsan:PrintAge() lisi:PrintAge()