Closures

hookmetamethod

Finds the named metamethod on a value and replaces that metamethod function with the provided replacement.

Syntax

hookmetamethod(object: any, metamethod: string, replacement: function): function

Arguments

NameTypeDescription
objectanyValue whose methods is inspected with raw metafield lookup.
metamethodstringMetafield name passed to raw metafield lookup.
replacementfunctionFunction passed to hookfunction as the replacement for the found metamethod function.

Returns

NameTypeDescription
originalfunctionCloned original metamethod closure returned by hookfunction.

Description

Finds the named metamethod on a value and replaces that metamethod function with the provided replacement. The metamethod name must be a string and the replacement must be a function.

Call it with 3 parameter(s): object, metamethod, replacement. The argument table explains which values are required and which ones only refine the behavior.

It returns original (function). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Hook an existing metamethod function.

local object = setmetatable({}, {
    __index = function(_, key)
        return key
    end,
})

local original
original = hookmetamethod(object, "__index", function(self, key)
    if key == "Name" then
        return "Real"
    end

    return original(self, key)
end)