Guide: Hooking
Replacing a function with your own, keeping the original callable, and not making it obvious.
Hooking swaps out a function for your own and gives you the original back so you can still call it. Most of the interesting stuff is built on it: watching remote calls, blocking an anti-cheat check, changing what a game function returns.
Three tools cover pretty much everything. hookfunction replaces a normal function. hookmetamethod replaces something in an object's metatable, which is how you hook __namecall (the most useful hook in Roblox). oth.hook is the low level one for C closures when you need the original under a few layers of hooks.
hookfunction takes the function and your replacement, and gives you back the original. Keep it, otherwise you can't call the real one.
local original
original = hookfunction(workspace.FindPartOnRay, function(self, ray, ignore, terrain, water)
-- Do your own thing, then fall through to the real one.
print("FindPartOnRay from", getcallingscript())
return original(self, ray, ignore, terrain, water)
end)Call the original unless you don't want to
A hook that just returns nil instead of calling the original will break the game in ways that are really hard to track down. Return original(...) unless blocking the call is the whole point.
Roblox compiles object:Method(args) into one __namecall call instead of an index and then a call. So one hook on __namecall sees *every* method call on every instance, including FireServer and InvokeServer.
local Players = game:GetService("Players")
local old
old = hookmetamethod(game, "__namecall", newcclosure(function(self, ...)
local method = getnamecallmethod()
if not checkcaller() and (method == "FireServer" or method == "InvokeServer") then
print(("%s:%s(%s)"):format(self:GetFullName(), method, table.concat({...}, ", ")))
end
return old(self, ...)
end))- getnamecallmethod() tells you which method got called. It only works inside the hook.
- checkcaller() is false when the game made the call and not you, which is how you avoid logging your own stuff.
- newcclosure wraps your function so it looks like a C closure. Without it, a game checking iscclosure(getrawmetatable(game).__namecall) will see the hook.
restorefunction puts a hooked function back to normal. Do this when your script unloads, because a hook that sticks around after its script is gone is a good way to break the next one.
local original = hookfunction(target, replacement)
-- ... later, when tearing down
restorefunction(target)isfunctionhooked tells you if a function already has a hook. Worth checking before adding a second one.
Everything is listed in Closures (hookfunction, newcclosure, restorefunction, setstackhidden), Metatable (hookmetamethod, getnamecallmethod, getrawmetatable) and OTH (oth.hook, oth.get_root_callback).