Constructor chaining

Classes / Constructors

local Man = {}
Man.__index = Man

-- The main constructor
function Man.new(name, country)
  return setmetatable({
    name = name,
    country = country,
  }, Man)
end

-- Another constructor calls the main one
function Man.from_name(name)
  return Man.new(name, "unknown")
end

local man1 = Man.new("Vladimir", "Russia")
-- man1.country = Russia

local man2 = Man.from_name("Vladimir")
-- man2.name = Vladimir
-- man2.country = unknown

print("man1.country = " .. man1.country)
print("man2.name = " .. man2.name)
print("man2.country = " .. man2.country)