/** * Sets the garbage collector callback method when items of a particular class are deleted * @param L A pointer to the Lua VM * @param ClassName The name of the class * When the class name specified does not exist, it is created. * @param GCHandler A function pointer * @return Returns true if successful, otherwise false. */ bool LuaBindhelper::setClassGCHandler(lua_State *L, const Common::String &className, lua_CFunction GCHandler) { #ifdef DEBUG int __startStackDepth = lua_gettop(L); #endif // Load the metatable onto the Lua stack if (!getMetatable(L, className)) return false; // Add the GC handler to the Metatable lua_pushstring(L, "__gc"); lua_pushcclosure(L, GCHandler, 0); lua_settable(L, -3); // Function is being permanently registed, so persistence can be ignored lua_pushstring(L, "__gc"); lua_gettable(L, -2); registerPermanent(L, className + ".__gc"); // Remove the metatable from the stack lua_pop(L, 1); #ifdef DEBUG assert(__startStackDepth == lua_gettop(L)); #endif return true; }
/** * Adds a set of methods to a Lua class * @param L A pointer to the Lua VM * @param ClassName The name of the class * When the class name specified does not exist, it is created. * @param Methods An array of function pointers along with their method names. * The array must be terminated with the enry (0, 0) * @return Returns true if successful, otherwise false. */ bool LuaBindhelper::addMethodsToClass(lua_State *L, const Common::String &className, const luaL_reg *methods) { #ifdef DEBUG int __startStackDepth = lua_gettop(L); #endif // Load the metatable onto the Lua stack if (!getMetatable(L, className)) return false; // Register each method in the Metatable for (; methods->name; ++methods) { lua_pushstring(L, methods->name); lua_pushcclosure(L, methods->func, 0); lua_settable(L, -3); // Function is being permanently registed, so persistence can be ignored lua_pushstring(L, methods->name); lua_gettable(L, -2); registerPermanent(L, className + "." + methods->name); } // Remove the metatable from the stack lua_pop(L, 1); #ifdef DEBUG assert(__startStackDepth == lua_gettop(L)); #endif return true; }
Value getGlobalMetamethod(Thread* t, CrocType type, String* name) { if(auto mt = getMetatable(t, type)) { if(auto ret = mt->get(name)) return *ret; } return Value::nullValue; }