Skip to content

Commit 72ccb5d

Browse files
committed
(builtin) Trace(scope, callback) form added to dbg
The system_load("builtin/debug.lua") got another form of invocation that should be more useful in an arcan context. Used like this: local list = {}; Trace(function_call_to_trace, function(msg) table.insert(list, msg) end) Would store the trace output into list and only for the passed function.
1 parent 275ec39 commit 72ccb5d

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

data/scripts/builtin/debug.lua

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,15 +49,15 @@ local function Indent(N)
4949
end
5050

5151
-- The hook function set by Trace:
52-
local function Hook(Event)
52+
local function Hook(tracer, Event)
5353
-- Info for the running function being called or returned from:
5454
local Running = GetInfo(2)
5555
-- Info for the function that called that function:
5656
local Caller = GetInfo(3, true)
5757
if not string.find(Running..Caller, "modules") then
5858
if Event == "call" then
5959
Depth = Depth + 1
60-
print(Indent(Depth), "calling ", Running, " from ",Caller, "\n")
60+
tracer(string.format("%s %s <- %s", Indent(Depth), Running, Caller));
6161
else
6262
local RetType
6363
if Event == "return" then
@@ -71,9 +71,18 @@ local function Hook(Event)
7171
end
7272
end
7373

74-
-- Sets a hook function that prints (to stderr) a trace of function
75-
-- calls and returns:
76-
function Trace()
74+
-- start tracing and send all data to stdout or provide a function scope to
75+
-- trace and a report function to send the data to
76+
function Trace(scope, reportfn)
77+
tracer = reportfn and reportfn or print;
78+
79+
if type(scope) == "function" then
80+
Trace(nil, reportfn)
81+
scope()
82+
Untrace()
83+
return;
84+
end
85+
7786
if not Depth then
7887
-- Before setting the hook, make an iterator that calls
7988
-- debug.getinfo repeatedly in search of the bottom of the stack:
@@ -89,7 +98,7 @@ function Trace()
8998
-- Don't count the iterator itself or the empty frame counted at
9099
-- the end of the loop:
91100
Depth = Depth - 2
92-
debug.sethook(Hook, "cr")
101+
debug.sethook(function(...) return Hook(tracer, ...) end, "cr")
93102
else
94103
-- Do nothing if Trace() is called twice.
95104
end

0 commit comments

Comments
 (0)