class
Animal = { name = "", age = 0 }
function Animal:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Animal:bark ()
print(self.name .. ': waor')
end
misha = Animal:new({ name = 'Misha', age = 12 })
misha:bark()
-- string: 'Misha: waor'
ps: 如果要使用self 关键字。new方法必须使用 :
声明。并且调用的时候也要记得用 :
extends
Cat = Animal:new()
function Pet:bark ()
print(self.name .. ': miao')
end
cat = Cat:new {name = 'as', age = 6 }
cat:bark()
VS Code snippet
"new class": {
"prefix": "newclass",
"body": [
"$1 = { $2 }",
"",
"function $1:new (o)",
" o = o or {}",
" setmetatable(o, self)",
" self.__index = self",
" return o",
"end",
"",
"$3"
]
}