After lua_pcall returns, jj is no longer on the call stack.
You can use lua_getinfo:
int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
Starting the what string with > pops a function from the stack, and fills out the debug structure with information based on the rest of the characters in the what string (see: lua_Debug for details).
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
int main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
const char *luaCode = "function jj() print('Hello from Lua!') end";
luaL_dostring(L, luaCode);
lua_getglobal(L, "jj");
lua_Debug ar;
if (lua_getinfo(L, ">Sn", &ar)) {
printf("Function (%s): %s\n", ar.what, ar.name ? ar.name : "(no name)");
printf("Source: %s\n", ar.short_src);
printf("Line: %d\n", ar.linedefined);
}
lua_close(L);
}
Function (Lua): (no name)
Source: [string "function jj() print('Hello from Lua!') end"]
Line: 1
Or set a hook with lua_sethook. Here is a hook that runs every time a function is called:
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
static void hook(lua_State *L, lua_Debug *ar)
{
if (LUA_HOOKCALL == ar->event && lua_getinfo(L, "Snl", ar)) {
printf("Function (%s): %s\n", ar->what, ar->name ? ar->name : "(no name)");
printf("Source: %s\n", ar->short_src);
printf("Line: %d\n", ar->currentline);
}
}
int main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
const char *luaCode = "function jj() print('Hello from Lua!') end";
luaL_dostring(L, luaCode);
lua_sethook(L, hook, LUA_MASKCALL, 0);
lua_getglobal(L, "jj");
lua_pcall(L, 0, 0, 0);
lua_close(L);
}
Function (Lua): (no name)
Source: [string "function jj() print('Hello from Lua!') end"]
Line: 1
Function (C): print
Source: [C]
Line: -1
Hello from Lua!
Whereas lua_getstack is for collecting the activation record for a currently active function call (which you can then use with lua_getinfo to collect debug information).
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
static int trace(lua_State *L)
{
lua_Debug ar;
if (lua_getstack(L, 1, &ar) && lua_getinfo(L, "Snl", &ar)) {
printf("Function (%s): %s\n", ar.what, ar.name ? ar.name : "(no name)");
printf("Source: %s\n", ar.short_src);
printf("Line: %d\n", ar.currentline);
}
return 0;
}
int main(void)
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
const char *luaCode = "function jj()\nprint('Hello from Lua!')\ntrace()\nend";
luaL_dostring(L, luaCode);
lua_register(L, "trace", trace);
lua_getglobal(L, "jj");
lua_pcall(L, 0, 0, 0);
lua_close(L);
}
Hello from Lua!
Function (Lua): (no name)
Source: [string "function jj()..."]
Line: 3
lua-apilua_pcall.