添加实例方法

扩展

local Point = {}
Point.__index = Point

function Point.new(x, y)
  return setmetatable({x = x, y = y}, Point)
end

local point1 = Point.new(1, 2)
local point2 = Point.new(2, 3)

-- The method is added to the class after the
-- objects were made: they find it in the class
function Point:distance_to(other)
  local dx = self.x - other.x
  local dy = self.y - other.y
  return math.sqrt(dx ^ 2 + dy ^ 2)
end

local distance = point1:distance_to(point2)
local text = string.format("%.4f", distance)
-- text = 1.4142

-- All strings share one metatable, its __index
-- is the string table: a new function there is
-- a method of every string, old ones too
local word = "hello"

function string.shout(value)
  return value:upper() .. "!"
end

local loud = word:shout()
-- loud = HELLO!

print("text = " .. text)
print("loud = " .. loud)