Lua多重继承代码实例

时间:2022-06-28 00:51:23

?

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

local function search(k, plist)

    for i, v in pairs(plist) do

        local temp_v = v[k]

        if temp_v then

            return temp_v

        end

    end

end

 

function createClass(...)

    local c = {}

    local parents = {...}

    

    --父类列表中搜索方法

    setmetatable(c, { __index = function(t, k) return search(k, parents) end } )

    c.__index = c

    

    --定义一个新的构造函数

    function c:new(o)

        o = o or {}

        setmetatable(o, c)

        return o

    end

    return c

end

 

Named = {}

 

function Named:getname()

    return self.name

end

 

function Named:setname(n)

    self.name = n

end

 

local NamedAccount = createClass(Account, Named)

account = NamedAccount:new({name = "Paul"})

print(account:getname())