Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local moon = require("moon")
- local super = moon.super
- local Property = moon.Property
- local classmethod = moon.classmethod
- local function class(...)
- local c = moon.class(...)
- _ENV[c.__name] = c
- _ENV.C = c
- end
- class("Food") do
- local C = C -- localize class for super
- function C:__init()
- self:make()
- end
- -- empty since we need a more specific type of food
- function C:make()
- end
- C.taste = Property(
- function(self)
- return 0
- end
- )
- end
- class("Noodles", Food) do
- local C = C
- function C:__init(cookTime)
- checkArg(1, cookTime, "number")
- self._cookTime = cookTime
- super(C, self).__init(self)
- end
- function C:make()
- super(C, self).make(self)
- print(string.format("cook noodles for %d minutes", self._cookTime))
- end
- C.taste = Property(
- function(self)
- return super(C, self).taste + 10 - math.abs(10 - self._cookTime)
- end
- )
- end
- class("Sauce", Food) do
- local C = C
- C.sauceTypes = {
- -- the position determines the taste
- "tomato",
- "cheese",
- "meat",
- }
- function C:__init(sauceType, ...)
- if self:getSauceTaste(sauceType) == 0 then
- error("Invalid sauce type", 2)
- end
- self._sauceType = sauceType
- super(C, self).__init(self, ...)
- end
- function C:make()
- super(C, self).make(self)
- print(string.format("cook %s sauce ", self._sauceType))
- end
- C.taste = Property(
- function(self)
- return super(C, self).taste + self:getSauceTaste(self._sauceType)
- end
- )
- -- class method
- C.getSauceTaste = classmethod(
- function(cls, sauceType)
- -- this is inefficient but for this example okay
- for i, ty in ipairs(cls.sauceTypes) do
- if ty == sauceType then
- return i * 10
- end
- end
- return 0
- end)
- end
- class("Pasta", Sauce, Noodles) do
- local C = C
- function C:make()
- print("cook pasta:")
- super(C, self).make(self)
- end
- end
- print(Pasta:getSauceTaste("cheese"))
- print()
- local pasta
- pasta = Noodles(15)
- print(pasta.taste)
- print()
- pasta = Pasta("tomato", 5)
- print(pasta.taste)
- print()
- pasta = Pasta("meat", 10)
- print(pasta.taste)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement