lua-users home
lua-l archive

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

The following Lua code causes an error, as expected, but (as of Lua
5.1.4) the error message is missing any file or line number

  table.sort({1,{2}}) --> "attempt to compare table with number"

This lack of information can be quite confusing for someone who
happens to sort the wrong table somewhere in a big script and doesn't
know what to make of the error message.

I'm not sure if this is an internal error in ltablib.c, but regardless
of that, I think Lua should be able to handle situations like this
better; even internal errors in a library should at least point to the
line of Lua code that triggered the error.

A small addition to the addinfo function in ldebug.c seems to greatly
improve the situation, something like:

 static void addinfo (lua_State *L, const char *msg) {
   CallInfo *ci = L->ci;
   if (isLua(ci)) {  /* is Lua code? */
     char buff[LUA_IDSIZE];  /* add file:line information */
     int line = currentline(L, ci);
     luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE);
     luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
+  else { /* it's not Lua code, but we can find the Lua code that called it */
+    lua_Debug ar;
+    if (lua_getstack(L, 1, &ar)) {  /* check function at level 1 */
+      lua_getinfo(L, "Sl", &ar);  /* get info about it */
+      if (ar.currentline > 0) {  /* is there info? */
+        luaO_pushfstring(L, "%s:%d: internal error: %s",
ar.short_src, ar.currentline, msg);
+      }
+    }
+  }