Posted by
| Nick Gammon
Australia (22,975 posts) bio
Forum Administrator |
Message
| The code below illustrates how to make a special debugging version of any Lua function (including the MUSHclient world functions).
What it does is save the original function into a local variable, and then replace the function of that name in the global table (_G) with a debug version.
The debug version accepts any number of arguments (by using "..."), and then displays:
- The name of the function that was called
- Where it was called from (function name and line number)
- A list of all the arguments which were sent to the function.
Then it calls the original function, passing any arguments that were sent to it.
It uses TraceOut to display this information, so to see it you need to turn Trace on (Game Menu -> Trace).
function DebugFunction (f)
assert (type (f) == "string" and type (_G [f]) == "function",
"DebugFunction must be called with a function name")
local old_f = _G [f] -- save original one for later
_G [f] = function (...) -- make new function
local t = debug.getinfo (2, "ln") -- get line and caller name
t.name = t.name or "<unknown place>"
TraceOut ("Function ", f, " called.") -- show name
TraceOut ("Called from ", t.name, " at line ", t.currentline) -- show caller
local n = select ("#", ...) -- number of arguments
if n == 0 then
TraceOut ("No arguments.")
else
for i = 1, n do -- show each argument
TraceOut ("Argument ", i, " = ", tostring ((select (i, ...))))
end -- for each argument
end -- have some arguments
old_f (...) -- call original function now
end -- debug version of the function
end -- DebugFunction
Now to use it, you call DebugFunction for each function you want to debug, passing the function name as an argument (you must get the spelling and capitalization exactly right):
DebugFunction ("ColourNote")
DebugFunction ("BroadcastPlugin")
This effectively replaces (in this example) ColourNote and BroadcastPlugin with debugging versions.
Now to test it:
function mytest ()
ColourNote ("red", "green", "hello, world") -- line 25
BroadcastPlugin (100, "some message") -- line 26
end -- mytest
mytest ()
Output
TRACE: Function ColourNote called.
TRACE: Called from mytest at line 25
TRACE: Argument 1 = red
TRACE: Argument 2 = green
TRACE: Argument 3 = hello, world
hello, world
TRACE: Function BroadcastPlugin called.
TRACE: Called from mytest at line 26
TRACE: Argument 1 = 100
TRACE: Argument 2 = some message
You can see from the trace output, that our debug version was called from "mytest" function, we are told the exact line number, and we are told the exact arguments. |
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|