带构造函数

类型初始化 / 结构体

-- A structure constructor is a plain function:
-- it returns a table, no metatable is set
local Size = {}
function Size.new(width, height)
  return {width = width, height = height}
end

-- f{...} is f({...}): fields are passed by name
local Point = {}
function Point.new(fields)
  return {top = fields.top, left = fields.left}
end

local Rectangle = {}
function Rectangle.new(size, point)
  return {size = size, point = point}
end

local size = Size.new(10, 10)
local point = Point.new{top = 5, left = 5}
local rect = Rectangle.new(size, point)
local width = rect.size.width
-- width = 10
local left = rect.point.left
-- left = 5

print("width = " .. width)
print("left = " .. left)