ReferenceClosures

hookmetamethod

Hooks one metamethod of an object's metatable.

Syntax

hookmetamethod(object: any, metamethod: string, hook: function) -> function

Also available as

hook_meta_method

Parameters

ParameterTypeDescription
objectanyA value with a metatable, such as game or any Instance.
metamethodstringThe metamethod to hook, for example "__index", "__newindex" or "__namecall".
hookfunctionThe function that runs instead of the metamethod.

Returns

TypeDescription
functionA callable copy of the original metamethod.

Description

It reads the raw metatable, even when the game has protected it with __metatable, and hooks the metamethod function with the same mechanism as hookfunction. Because all Instances share one metatable, hooking __index or __namecall on game affects every Instance.

On an Instance, a malformed __index or __namecall call (wrong self type, a non-string key, missing arguments) goes straight to the original and raises its error without running the hook.

Inside a __namecall hook, getnamecallmethod returns the method name being called.

Example

local oldIndex
oldIndex = hookmetamethod(game, "__index", function(self, key)
    if not checkcaller() and key == "WalkSpeed" then
        return 16
    end
    return oldIndex(self, key)
end)

local oldNamecall
oldNamecall = hookmetamethod(game, "__namecall", function(self, ...)
    if getnamecallmethod() == "FireServer" then
        print("FireServer on", self:GetFullName())
    end
    return oldNamecall(self, ...)
end)

Notes

These are Game executor contracts. Check build requirements and session lifetimes before using them.