3
votes

Say I have two C functions registered in my Lua scope:

int func1(lua_State* L)
{
    int n = lua_gettop(L);
    // Do sth here...
}

int func2(lua_State* L)
{
    int n = lua_gettop(L);
    // Do sth here...
}

The question is: can I call func2 within func1?

I found out that if several arguments are passed to func1, the value that lua_gettop() returns in func2 makes no sense.

For example, if 3 arguments are passed to func1 in my lua script, lua_gettop() returns 3 in func1, and no less than 3 in func2. This is definitely wrong since lua_gettop() should return the number of arguments passed to current function.

So should I do any stack trick before calling func2 such as setting up new stack frame or just simply should not do this?

2

2 Answers

4
votes

lua_gettop does not return number of arguments, but rather number of items on your stack. If you mess with the stack in the calling function, it will remain messed up when you directly call another C function.

If you call it via Lua (for example using lua_cpcall), it will start with it own stack state and arguments you give it within Lua.

0
votes

No you shouldn't call directly func2 within func1, each function has a local stack.

As @che wrote, lua_gettop returns the number of items in your stack, so you can use lua_gettop to get the arguments passed to a function because each function has a local stack.

That's why for getting the arguments of a function you do like this:

lua_tostring(L, 1);
lua_tointeger(L, 2);
lua_to...(L, i);

And for returning results you push back into the local stack:

lua_pushstring(L, "hello");
lua_pushinteger(L, 1);

return 2; // number of arguments returned

If you want to call a lua function from C use lua_pcall.