4

I was wondering if there is any way to escape the __metatable metamethod. I know there isn't one, but I'm trying to do something like this, but obviously __metatable blocks that from happening:

    -- pretend that there is a __metatable field given to a table
    setmetatable(_G, {__index = {None="No indexes"}})
    -- error: (the string given to the __metatable metamethod)

What I am trying to do here is simply escape past the __metatable field and simply allow myself to set a metatable on _G, which already has one. I know it is impossible to do this, but I'd like to ask if there is still a chance to bypass?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183

2 Answers2

5

The only way to do this from Lua is to use debug.setmetatable.

The whole point of __metatable is protection. The debug library bypasses this protection (and others) and should be used with care, of course.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 5
    `lua_setmetatable` from the C API would work too. And some metatables are reused as index tables (something like `mt.__index = mt`) -- in that case you can simply set `aTable.__index.__metatable = nil` to remove the protection. – siffiejoe Mar 29 '15 at 13:19
-3

I would just override the metables.

You can do that by using synapse x overridemetables().

Red
  • 26,798
  • 7
  • 36
  • 58
  • 3
    It appears to me that you did not understood the question. It is talking about Lua mechanism of metatables, while your answer talks about "metables" and presents piece of code that is not valid Lua in any capacity. – val - disappointed in SE Jan 21 '21 at 17:43