summaryrefslogtreecommitdiff
path: root/Data/Libraries/Penlight/tests/lua/animal.lua
blob: 9366db9f0d76f7b5685019c87ff61d9bd65c76e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
-- Module containing classes
local class = require 'pl.class'
local utils = require 'pl.utils'
local error = error
if utils.lua51 then
    module 'animal'
else
    _ENV = {}
end

class.Animal()

function Animal:_init(name)
   self.name = name
end

function Animal:__tostring()
    return self.name..': '..self:speak()
end

class.Dog(Animal)

function Dog:speak()
    return 'bark'
end

class.Cat(Animal)

function Cat:_init(name,breed)
   self:super(name)  -- must init base!
   self.breed = breed
end

function Cat:speak()
    return 'meow'
end

-- you may declare the methods in-line like so;
-- note the meaning of `_base`!
class.Lion {
    _base = Cat;
    speak = function(self)
        return 'roar'
    end
}

-- a class may handle unknown methods with `catch`:
Lion:catch(function(self,name)
    return function() error("no such method "..name,2) end
end)

if not utils.lua51 then
   return _ENV
end