lua(仿类)

Account = {
  balance = 0
}

function Account:deposit(v)
  self.balance = self.balance + v
end

function Account:new(o)
  o = o or {}
  setmetatable(o, self)--Account表本身作为o的metatable
  self.__index = self--自己作为自己的原型??
  return o
end

a = Account:new{balance = 0}

--调用a的deposit,他会查找a的metametable的_index对应的表
--getmetatable(a).__index(a, 100)
--最终调用的是Account的deposit即Account.deposit(a, 100.00)
a:deposit(100.00)--通过这种方法调用了原始的Account的deposit

--将会继承默认的balance的值
b = Account:new()
print(b.balance)--b.balance等于0,下次访问此值时,不会涉及__index,b已经存在自己的balance域

--通过这种方法可以模拟面向对象,Account是类,而创建出来的b是这个类的对象
原文地址:https://www.cnblogs.com/zzyoucan/p/4325384.html