您的位置:首页 > 编程语言 > Lua

在lua中创建类和对象

2013-10-24 00:37 393 查看
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继承了所有的方法和变量,还可以重写方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: