lua-users home
lua-l archive

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


Rather than using upvalues, I store the metatable in the registry.  Gives me better performance than using luaL_checkudata and can be used without relying on upvalues.  This is especially helpful if you have to deal with multiple different types of userdata.

luaL_newmetatable(L, "MyType");
my_type_ref = luaL_ref(L, LUA_REGISTRYINDEX);

int is_type(lua_State *L, int type_ref, int idx) {
    if(!lua_getmetatable(L,idx)) return 0;
    lua_rawgeti(L, LUA_REGISTRYINDEX, type_ref);
    if(lua_rawequal(L,-1,-2)) { lua_pop(L,2); return 1; }
    lua_pop(L,2);
    return 0;
}

if(!is_type(L, my_type_ref, 1)) {
    ...
}