local Shape = {}
Shape.__index = Shape
function Shape.new(line_count, name)
return setmetatable({line_count = line_count,
name = name}, Shape)
end
function Shape:describe()
return self.name .. " has "
.. self.line_count .. " lines"
end
-- Неполная копия: вложенные таблицы были бы общими
function Shape:copy()
local copy = {}
for key, value in pairs(self) do
copy[key] = value
end
-- Тот же класс, поэтому методы работают
return setmetatable(copy, getmetatable(self))
end
local square = Shape.new(4, "Square")
local square_copy = square:copy()
-- Копия не меняется вслед за оригиналом
square.name = "Box"
local copy_name = square_copy.name
-- copy_name = Square
local text = square_copy:describe()
-- text = Square has 4 lines
print("copy_name = " .. copy_name)
print("text = " .. text)