防止Lua表中的函数覆盖

时间:2014-05-22 09:16:29

标签: eclipse lua override lua-table

在我的程序中为同一个表定义了两个具有相同名称的函数时,我希望我的程序发出错误。发生的事情是它只是调用最后一个函数并执行它。

以下是示例代码

Class{'Cat'}

function Cat:meow( )
  print("Meow!")
end

function Cat:meow()
  print("Mmm")
end

kitty = Cat:create()
kitty:meow()

执行结果仅为:“嗯” 相反,我希望给出类似错误消息的内容。

1 个答案:

答案 0 :(得分:3)

不幸的是,__newindex不拦截已经存在的字段的分配。因此,唯一的方法是保持Cat为空并将其所有内容存储在代理表中。

我不知道您的OOP库的性质,所以您必须自己合并这个示例:

local Cat_mt = {}

-- Hide the proxy table in closures.
do
  local proxy = {}

  function Cat_mt:__index(key)
    return proxy[key]
  end

  function Cat_mt:__newindex(key, value)
    if proxy[key] ~= nil then
      error("Don't change that!")
    end
    proxy[key] = value
  end
end

Cat = setmetatable({}, Cat_mt)