Lua Hook/Patching Implementation

Hello again fellow developers! :wave:

This module is a Hooking Implementation written in lua, influenced by the Harmony Libary

!! Harmony is not a Hooking libary, more a less a C# Patching libary, This is just an implementation of lua hooking, influenced by the Harmony libary !!

Example

The example below is a demonstration on how you might use the hook libary to your advantage

local HookModule = require(script.ModuleScript)
local AddFunction = HookModule.new(function(Int0, Int1)
	return Int0 + Int1
end)

AddFunction:Prefix(function(Int0, Int1)
	if type(Int0) ~= "number" then return false end
	if type(Int1) ~= "number" then return false end
	
	return true
end)

AddFunction:Postfix(function(Value)
	return Value, "Some Postfix Argument!"
end)

-- we can change the logic of `AddFunction` instead, we could multiply the given values!
-- AddFunction:Prefix(function(Int0, Int1)
--  	return Int0 * Int1
-- end)

local Number, PostFixArg = AddFunction(5, 5)

print(Number, PostFixArg)
Source
--[[
    HooksModule.lua

    @Author: AsynchronousMatrix
    @Licence: ...


]]--

-- // Variables
local HooksModule = { }
local HookFunction = { }

HookFunction.__index = HookFunction
HookFunction.__call = function(Hook, ...)
    return Hook:Invoke(...)
end

-- // HookFunction Functions
function HookFunction:Prefix(Callback)
    assert(type(Callback) == "function", "Expected Argument #1 function")
    
    self._PrefixCallback = Callback
end

function HookFunction:Postfix(Callback)
    assert(type(Callback) == "function", "Expected Argument #1 function")

    self._PostfixCallback = Callback
end

function HookFunction:Patch(Callback)
    assert(type(Callback) == "function", "Expected Argument #1 function")
    
    self.Callback = Callback
end

function HookFunction:Invoke(...)
    if not self.Callback then return end

    if self._PrefixCallback then
        local Continue, Exception = self._PrefixCallback(...)

        if not Continue then return Exception end
    end
    
    if self._PostfixCallback then
        return self._PostfixCallback(
            self.Callback(...)
        )
    end

    return self.Callback(...)
end

-- // HooksModule Functions
function HooksModule.new(Callback)
    local Hook = setmetatable({ Callback = Callback }, HookFunction)

    return Hook
end

-- // Module
return HooksModulee

GitHub Link;
https://github.com/4x8Matrix/Hook-Module

If anyone has any suggestions, feel free to leave a comment below; I’ll respond when I am able too! :wave:

4 Likes