you can see my repo:
https://github.com/starwing/lbind/tree/newinterface/runtime
this is a C module that has many useful snippet, one useful for this issue is lbind_setmetafield.
A small C snippet can solve this issue (untested):
static int protect_index(lua_State *L) {
lua_rawget(L, 1);
if (lua_isnil(L, -1)) luaL_error(L, "....", luaL_tolstring(L, 2, NULL));
return 1;
}
static int protect(lua_State *L) {
lua_pushcfunction(L, protect_index);
lbind_setmetafield(L, 1, "__index");
lua_settop(L, 1);
return 1;
}