3

I create a userobject in C, and as part of this I create a metatable to override methods like __tostring, __index, etc. I noticed, though, that it's possible to retrieve the object's metatable through getmetatable(). It seems that it's possible to make getmetatable() return any arbitrary table, if my metatable has a __metatable key. I'd like getmetatable() to return nil, so my first thought was to add a __metatable key with nil, but that obviously doesn't work as it doesn't actually add the __metatable key to the metatable:

struct my_obj* obj = (struct my_obj*)lua_newuserdata(L, sizeof(struct my_obj));
if (luaL_newmetatable(L, "mymetatable") != 0) {
    lua_pushliteral(L, "__metatable");
    lua_pushnil(L);
    lua_rawset(L, -3); /* will not work, can not add a nil... */
}
lua_setmetatable(L, -2);

Can this be done somehow, or do I have to stick with stuffing an empty table into __metatable?

Tom
  • 653
  • 1
  • 8
  • 15

2 Answers2

1

Redefine getmetatable to return nil if the table has a __metatable key.

lhf
  • 70,581
  • 9
  • 108
  • 149
0

Good question.

I don't see any way of getting this to work in lua (5.1, 5.2 or 5.3) given a quick look at the manual and code involved.

I'd wondered if there were some __call/etc. games you could play to make this work but the lookups are raw and don't do much checking beyond "is nil".

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148