I'm trying to improve error handling in my program that runs a Lua script. Simplified version:
function _errH(msg)
print(msg .. "\n" .. debug.traceback(nil, 1))
end
function _main()
-- cause some random error
print(a-2)
end
function main()
xpcall(_main, errH)
end
main()
Gives me the following call stack (please ignore the wrong line numbers):
stack traceback:
[string ""]:7428: in function '__sub'
[string ""]:7651: in function <[string ""]:7432>
[C]: in function 'xpcall'
[string ""]:7658: in function 'main'
[string ""]:7928: in main chunk
Now I'm wondering why there is [string ""]
everywhere.
Is there any way to influence these missing texts? Do I have to name the functions in addition to defining them?
Why do I see in function '__sub'
but not in function '_main'
for example?
Generally you can assign the chunk name when loading. The auxiliary function use lua_load
and most will set the chunk name based on the type of content being loaded:
lua_load
accepts a chunk nameluaL_loadfile
will use the filenameluaL_dofile
uses luaL_loadfile
luaL_loadstring
will use the string contentsluaL_dostring
uses luaL_loadstring
luaL_loadbuffer
accepts a chunk nameIf you look at the source code for luaL_loadstring:
LUALIB_API int luaL_loadstring (lua_State *L, const char *s) {
return luaL_loadbuffer(L, s, strlen(s), s);
}
Notice that its really just a convenience function that calls luaL_loadbuffer
with the string as the chunk name. So, what is needed is to load your code from strings like:
luaL_loadbuffer(L, s, strlen(s), "=my_chunk");
Where "=my_chunk"
is the name of the chunk that will appear in the debug information.
The equal sign before the name changes the trace back:
my_chunk:1: in main chunk
Where omitting the equal sign will show:
[string "my_chunk"]:1: in main chunk