What is the best way to deal with nested lua_CFunction calls? Assume I have two function like this:
static int function2(lua_State *L) {
int i = luaL_checkint(L, 1);
/* do something */
return 1;
};
static int function1(lua_State *L) {
struct udata *u = luaL_checkudata(L, 1, UDATA_METATABLE);
int i = luaL_checkint(L, 2);
/* do something */
/* this does not work, first on call stack is udata, not int */
return function2(L);
};
The function call as above does not work. One option is to modify function2()
to use the last element (index -1) on stack, but this is not a sollution in general since function2()
might be called from various places with different call stacks.
Another way would be to replace the return function2(L);
by
lua_pushcfunction(L, function2);
lua_pushvalue(L, 2);
lua_call(L, 1, 1); /* need to know number of results */
I assume this gives function2()
its own call stack so there is no need to modify it. But this sollution seems overly complicated for functions with more parameters since it requires duplicating all of them on the stack.
tl;dr: What is the recommended way/a good way to call a lua_CFunction
from inside another one?
In
function1
you are expecting the bottom of the stack to be user data. When you callfunction2
directly, the LuaState has not changed and therefore the bottom is still user data.You can successfully call
function2
fromfunction1
by ensuring an integer is at index 1.You could do this by calling
lua_insert(L, 1)
which will move the top (assuming index 2), to index 1.You could also do this by popping all values the pushing the integer back on: