简体   繁体   中英

Lua & C++ API getting the executing information

In Lua I have a function called utils.debug() and what I would like to do is use it in my Lua code as follows:

function Foo:doSomething
    if (/* something */) then
        print("Success!")
    else
        utils.debug()
    end
end

function Foo:doSomethingElse
    if (/* something else */) then
        print("Awesome!")
    else
        utils.debug()
    end
end

I would like to use it throughout my Lua code to help me debug. As a result, I would like my C++ code to know where in the Lua code the utils.debug() was called from. I looked into lua_Debug and lua_getinfo and they seem pretty close to what I want, but I'm missing a piece:

int MyLua::debug(lua_State* L)
{
    lua_Debug ar;
    lua_getstack(L, 1, &ar);
    lua_getinfo(L, ??????, &ar);

    // print out relevant info from 'ar' 
    // such as in what function it was called, line number, etc
}

Is this what the lua_Debug struct is for or is there another facility or method I should use to do this?

This is what I use to produce a Lua stack trace:

lua_Debug info;
int level = 0;
while (lua_getstack(l, level, &info)) {
    lua_getinfo(l, "nSl", &info);
    fprintf(stderr, "  [%d] %s:%d -- %s [%s]\n",
        level, info.short_src, info.currentline,
        (info.name ? info.name : "<unknown>"), info.what);
    ++level;
}

See the documentation for lua_getinfo for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM