有没有办法在Lua中的某些if条件下使用Parent的函数

时间:2018-03-19 22:57:46

标签: inheritance lua

我正在尝试覆盖子foo()中的A个父B。但不是完全覆盖它,我想只在某些条件下覆盖它。伪示例将是:

function B.foo()
  if #Certain conditions# then
    # Do what I want to overwrite #
  else
    # Do what the parent wants
  end
end

我不能再把父母实现放在这里,因为我无法访问父代码。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

我认为" B是父级B"您的意思是您已将A metatable索引设置为B.foo。因此,在您向A.foo分配新内容之前,它会解析为B.foo的值。只需将其保存到本地upvalue,并使用此引用调用local parent_foo = B.foo -- save current B.foo, presumably pointing to A.foo at the moment function B.foo() -- replace it with new B.foo if #Certain conditions# then # Do what I want to overwrite # else return parent_foo() end end 指向的任何内容,直到您分配了新的实现。

my-video
相关问题