lua-users home
lua-l archive

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


It seems impossible to get the filename in the self-defined hook
function (lua-5.3.5).

Although there is a "source" field of the structure named `lua_Debug`.
But I really could not get the right filename indeed after I did several tests.

It seems that this field has not been assigned to the right value in the
luaD_hook() function.

I tried to add some code snippet to make it work(i.e getting the filename in the
self-defined hook function which is set by lua_sethook()).
Are there some potential problems that I should be aware of as adding the code
snippet?

I would be grateful to have some help with this question.

Here is the related code snippet:
#define ADD_FILE_INFO
void luaD_hook (lua_State *L, int event, int line) {
  lua_Hook hook = L->hook;
  if (hook && L->allowhook) {  /* make sure there is a hook */
    CallInfo *ci = L->ci;
    ptrdiff_t top = savestack(L, L->top);
    ptrdiff_t ci_top = savestack(L, ci->top);
    lua_Debug ar;
    ar.event = event;
    ar.currentline = line;
    ar.i_ci = ci;

    #ifdef ADD_FILE_INFO   //added by me
    StkId func = ci->func;
    Closure *cl = ttisclosure(func) ? clvalue(func) : NULL;
    lua_assert(ttisfunction(ci->func));
    Proto *p = cl->l.p;
    ar.source = p->source ? getstr(p->source) : "=?";
    ar.linedefined = p->linedefined;
    ar.lastlinedefined = p->lastlinedefined;
    ar.what = (ar.linedefined == 0) ? "main" : "Lua";
    #endif

    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
    ci->top = L->top + LUA_MINSTACK;
    lua_assert(ci->top <= L->stack_last);
    L->allowhook = 0;  /* cannot call hooks inside a hook */
    ci->callstatus |= CIST_HOOKED;
    lua_unlock(L);
    (*hook)(L, &ar);
    lua_lock(L);
    lua_assert(!L->allowhook);
    L->allowhook = 1;
    ci->top = restorestack(L, ci_top);
    L->top = restorestack(L, top);
    ci->callstatus &= ~CIST_HOOKED;
  }
}