Lua继承问题(尝试调用字段'String'(a nil value))

我在Lua的继承中遇到了困难。 我收到了一个错误

“错误:main.lua:32:尝试调用字段'String'(a nil value)”

我理解错了什么吗? 我不明白我的例子与:[https://www.lua.org/pil/16.2.html]有何不同(https://www.lua.org/pil/16.2.html)

Animal = {}

function Animal:New()
    a = {}
    setmetatable(a,Animal)
    a.__index = Animal

    return a
end

function Animal:String()
    print(“我是动物”)
end

Cat = {}

function Cat:New()
    c = Animal:New()
    setmetatable(c,Cat) - 设置元表为Cat
    c.__index = Animal - 继承自动物

    返回c
end

--覆盖吠叫
function Cat:String()
    print(“我是猫”)
end

c = Cat:New() - 应该返回猫
print(c:String())
点赞
用户3574628
用户3574628

以下是你的代码和 PiL 示例之间几个不同之处:

  1. Account.new 使用 self 而非 Account 作为新对象的元表。self 可能指向 Account 或任何子类。

  2. Account.newself 上设置了 __index,而非新对象。这是必须的,因为元方法必须放在元表而非对象本身上才有任何效果。

  3. SpecialAccount 是使用 Account:new() 创建的,而非一个空的平凡表。请注意,该系统使用 new 方法来创建子类和实例。

  4. SpecialAccount 没有定义 new 方法。它只是继承了 Account 中的一个。

错误是由于 c 的元表是 Cat,但是 Cat 没有 __index 所致。SpecialAccount__index 是通过它的 new 方法设置的,当它创建一个实例时。

2021-08-15 16:54:43