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)