lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Wesley Smith wrote:
Hi list,
I'm just starting to dive into the debug module after a few years of
ignoring it and am wondering what the best strategies for using it
are, particularly for the following scenario:

I am evaluating chunks of code using loadstring and pcall.  Let's say
I define a function test

function test()
	x = x+1

where x is undefined (e.g. nil).  Next, I evaluate another chunk that
calls test as follows:


When I run the compiled chunk that calls test, I get an error saying:
[string "..."]:4: attempt to perform arithmetic on global 'x' (a nil
value, which is what I expected.  Now, I want to highlight the line of
code where this error occurred.  For that, I need to somehow trace
back from the second chunk to the first.  This is what I'm not sure
how to do.

Imagine that I can store the chunks with their line number ranges in
the text editor and can somehow give them a unique ID.  Given that an
error occurs when I run the second chunk, how can I identify the fact
that it's actually generating an error within the code of the first
chunk?  I have the line number within this chunk from the error
returned by pcall, but I'm not sure how to derive the fact that the
function "test" was defined in the first chunk.

loadstring takes a second argument which you can use to identify the chunk:

loadstring(chunk, chunk_id)

where chunk_id could/should be prepended with "=", e.g.

loadstring([[ error('BOOM!') ]], '=chunk_42')()
chunk_42:1: BOOM!
stack traceback:
	[C]: in function 'error'
	chunk_42:1: in main chunk
	stdin:1: in main chunk
	[C]: in ?


Richard Hundt