Copying an object

Classes

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

-- Shallow copy: nested tables would be shared
function Shape:copy()
  local copy = {}
  for key, value in pairs(self) do
    copy[key] = value
  end
  -- The same class, so the methods work
  return setmetatable(copy, getmetatable(self))
end

local square = Shape.new(4, "Square")
local square_copy = square:copy()

-- The copy does not follow the original
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)