2

In my program when two functions with the same name are defined for the same table, I want my program to give an error. What's happening is that it's simply just calling the last function and executing it.

Here's a sample code

Class{'Cat'}

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

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

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

The result of the execution is only: "Mmm" Instead I want something like an error message to be given.

Luna28
  • 527
  • 3
  • 15
  • I have already written a Metatable and functions which create a table with the name of the parameter passed to the function Class – Luna28 May 22 '14 at 09:18

1 Answers1

3

Unfortunately, __newindex does not intercept assignments to fields which already exist. So the only way to do this is to keep Cat empty and store all its contents in a proxy table.

I don't know the nature of your OOP library, so you'll have to incorporate this example on your own:

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)
luther
  • 5,195
  • 1
  • 14
  • 24