lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello,

I noticed that setmetatable({}, nil) works normally, but setmetatable({})
causes an argument type error. This patch fixes the error and restores
expected behavior.

When calling setmetatable() with 1 argument, the lua_type() call returns
LUA_TNONE, which fails the condition in the following luaL_argcheck() because
it only checks for a table or an _explicit_ nil, despite having an identical
meaning. By moving lua_settop(L, 2) to the beginning of the function, a
1-argument stack is extended with an explicit nil, and a 2-argument (or more)
stack behaves the same as before.

Regards,
Nathaniel

lbaselib.c
@@ -125,11 +125,11 @@
  static int luaB_setmetatable (lua_State *L) {
+  lua_settop(L, 2);
   int t = lua_type(L, 2);
   luaL_checktype(L, 1, LUA_TTABLE);
   luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
                     "nil or table expected");
   if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
     return luaL_error(L, "cannot change a protected metatable");
-  lua_settop(L, 2);
   lua_setmetatable(L, 1);
   return 1;
 }