Account = {balance = 10}
function Account:withdraw (v)
self.balance = self.balance - v
end
function Account:deposit (v)
self.balance = self.balance + v
end
function Account:create()
local o = {}
setmetatable(o, self)
self.__index = self
return o
end
a = Account:create()
--重写基类方法
function a:deposit(v)
print("hello world")
end
print(a.balance)
a:deposit(100)
lua中没有类,但通过setmetatable和__index可以仿制一个类,a就从Account继承了所有的方法和变量,还可以重写方法
在lua中创建类和对象
最新推荐文章于 2024-04-27 21:37:38 发布