lua-users home
lua-l archive

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


Hi,
I would like to install a metatable for global environment _G from C code.

http://lua-users.org/wiki/DetectingUndefinedVariables

gives a way to do this in Lua code (see the function GLOBAL_lock) on this page.

function GLOBAL_lock(t)
  local mt = getmetatable(t) or {}
  mt.__newindex = lock_new_index
  setmetatable(t, mt)
end

I tried to use the following code in my C program:

void GLOBAL_lock (lua_State *L) {
  luaL_newmetatable( L, "_G"));
  lua_pushvalue(L, -1); /* duplicate the metatable */
  lua_setfield(L, -2, "__index");
  lua_pushcfunction( L, lock_new_index);
  lua_setfield( L, -2, "__newindex");
  luaL_setmetatable( L, "_G");
}

This compiles fine, and if I check lua_gettop at end of this function,
also all fine, also luaL_getmetatable will then return me some table
for "_G"... . So it looks as if it has worked.

But my function lock_new_index  (int lock_new_index( lua_State *L) {
... } ) is never invoked.

Can anybody give me some hint, what code in my C program might be
wrong / missing to get this run?