-- Person= {} -- function Person:new(fName, lName) -- local obj= {} obj.firstName = fName obj.lastName = lName -- function obj:getName() return self.firstName end -- ! setmetatable(obj, self) self.__index = self; return obj end -- vasya = Person:new("", "") -- print(vasya.firstName) --> : -- print(vasya:getName()) --> :
Woman = {} -- setmetatable(Woman ,{__index = Person}) -- masha = Woman:new("","") print(masha:getName()) --->:
function extended (child, parent) setmetatable(child,{__index = parent}) end
Woman = {}; -- extended(Woman, Person) -- masha = Woman:new("","") print(masha:getName()) --->:
Person = {} function Person:new(name) local private = {} -- private.age = 18 local public = {} -- public.name = name or "" -- "" - -- function public:getAge() return private.age end setmetatable(public,self) self.__index = self; return public end vasya = Person:new() print(vasya.name) --> : print(vasya.age) --> : nil print(vasya:getAge()) --> : 18
Person = {} function Person:new(name) local private = {} private.age = 18 local public = {} public.name = name or "" -- , function public:getName() return "Person protected "..self.name end -- , function Person:getName2() return "Person "..self.name end setmetatable(public,self) self.__index = self; return public end -- , Person Woman = {} extended(Woman, Person) -- -- function Woman:getName() return "Woman protected "..self.name end -- getName2() function Woman:getName2() return "Woman "..self.name end -- masha = Woman:new() print(masha:getName()) --> Person protected print(masha:getName2()) --> Woman
Person = {} function Person:new(name) local private = {} private.age = 18 local public = {} public.name = name or "" -- , function public:getName() return "Person protected "..self.name end setmetatable(public,self) self.__index = self; return public end -- , function Person:getName2() return "Person "..self.name end
-- , Person Woman = {} extended(Woman, Person) -- -- setName function Woman:getName2() return "Woman "..self.name end print(masha:getName2()) --> Woman -- print(Person.getName2(masha)) --> Person
function extended (child, parent) setmetatable(child,{__index = parent}) end Person = {} function Person:new(name) local private = {} private.age = 18 local public = {} public.name = name or "" -- , function public:getName() return "Person protected "..self.name end -- function Person:getName2() return "Person "..self.name end setmetatable(public,self) self.__index = self; return public end -- , Person Woman = {} extended(Woman, Person) -- -- setName function Woman:getName2() return "Woman "..self.name end masha = Woman:new() print(masha:getName2()) --> Woman -- print(Person.getName2(masha)) --> Person
Source: https://habr.com/ru/post/259265/
All Articles