Basically I'm just wondering if it's possible for a script to find out what line of code it's on. For example, say you wanted to make a custom error handler
, and have a function return
(as a string
value), what line of code
the error was on. How would this be done? Is this even possible?
Here's what I made for my error handler so far, but it's kinda useless since it's just different ways to use the error function:
local function errorCheck(v,err) if not v then error("Error: "..tostring(err)) end return true end print(errorCheck(nil,"the value is nil")) -- pretty much just the assert function
But instead of the script breaking, I'd want it to only return the line
that the error is on, and that's it.
P.S:
LoadStringEnabled
is disabled
, and I don't want to use loadstring
for this.
Simplified question:
How do I find the line of code a function call is on?
debug.traceback()
is a function that provides the current call-stack (as a string).
Thus print( debug.traceback() )
will make something that looks fairly like an error message, where the first line is the current line, and the second is the caller, etc.
Here's a simple function which cleans up the trace. Warning: this will fail on many things, it makes a lot of assumptions.
function trace() local msg = debug.traceback() local t = {} for x in msg:gmatch("[^\n]+") do local source, line, message = x:match("^(.+):(%d+):%s+(.+)$") if message then table.insert(t, {source = source, line = line * 1, message = message}) end end table.remove(t, 1) -- hide trace implementation return t end
Keep in mind that scripts can have :
s in their names, messages could have colons and newlines (maybe?), and that tail-recursive1 calls get weird output that this will ignore
EDIT ROBLOX does not support tail calls, so this can be disregarded ↩
If you pause the test in Studio, and you check the script, it should have a line in it, unless it is completely carried out, highlighted in yellow with a yellow pointer.
Hope this helped ;)
I think this might be what you are looking for.
game:GetService("ScriptContext").Error:connect(function(message, trace, script) print(script:GetFullName().." errored!") print("Reason: "..message) print("Trace: "..trace) end