blob: b6c31e3e532d9999b58c2d75be776ba97757e125 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# Tut 0x021
## Detouring
Detouring is a method commonly used in Lua, even outside of Garry's Mod development. The idea is to redirect a function through your function first, then call the function you're redirecting at the end (or maybe the beginning, or anywhere really). Let's see an example:
garrysmod/lua/autorun/detourprint.lua
local oldprint = print
function print(...)
local args = {...}
args[#args + 1] = "if you know what I mean..."
oldprint(unpack(args))
end
The above script __replaces__ the print function with a new function which eventually calls the original print function with modified arguments. The above can be done with modules in Artery as well. For example, `log.lua`'s .error() function currently only prints a message in red, it doesn't actually show what failed or why. Let's modify it to show a stack trace.
garrysmod/addons/artery\_rougelite/trace\_errors.lua
local log = nrequire("log.lua")
local colors = nrequire("config/colortheme.lua") --Holds colors
local oldlog = log.error
function log.error(...)
oldlog(unpack({...}))
MsgC(colors.console.red,debug.traceback())
end
For more information on colortheme.lua see @{colortheme.lua}, for more on debug.traceback() see [the Gmod wiki](http://wiki.garrysmod.com/page/debug/traceback).
***Note*** : When detouring, mind the order that you do your logic and the logic that was there before. Does it make sense to do your function first? Maybe it makes more sense to do the usual logic, then come back to your function to do more stuff.
***Note 2***: Be sure you pass ALL the arguments from the original function through your function. Even if you don't need them, someone else might! If the target function takes a variable number of arguments (It has `...` in the function signature), you must also have `...` in your function signature to capture all arguments.
Next tutorial: @{tut030_inventories.md}
|