lua-users home
lua-l archive

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


On Feb 21, 2018, at 10:28 AM, Andrew Gierth <andrew@tao11.riddles.org.uk> wrote:

>>>>>> "albertmcchan" == albertmcchan  <albertmcchan@yahoo.com> writes:
> 
> albertmcchan> Had not expected calling B shared the same lua stack.
> albertmcchan> Is there a way to force calling B, C, ... with a new
> albertmcchan> stack ? (like in lua ?)
> 
> Of course there is, you use lua_pushcfuncfion and lua_call, as I pointed
> out to you before.
> 
> int B(lua_State *L)
> {
>    lua_settop(L, 0);
>    lua_pushstring(L, "foo!");
>    return 1;
> }
> 
> int A(lua_State *L)
> {
>    /* stack currently has args of A if any */
>    lua_pushstring(L, "bar!");
>    /* this calls B in A's stack frame, so it will clobber the
>     * string pushed above and any args, leaving A's stack with
>     * just B's "foo!" on it
>     */
>    B(L);
>    /* but this calls B on a brand new stack frame of its own,
>     * so the existing "foo!" remains on the stack and another
>     * one is pushed on top
>     */
>    lua_pushcfunction(L, B);
>    lua_call(L, 0, 1);  /* 0 args, 1 result */
>    /* stack now has just "foo!", "foo!" */
>    return 2;
> }
> 
> This is how you do it if B and A both need to be independently callable
> from Lua but A needs to call B.
> 
> -- 
> Andrew.

Thanks Andrew,
Can I assume call B with argument "foo!", "whatever" like this ?

lua_pushcfunction(L, B);          // stack = foo! B
lua_pushvalues(L, -1);             // stack = foo! B foo!
lua_pushstring(L, "whatever");
lua_call(L, 2, 1);                       // == lua call B("foo!", "whatever")
return 2;                                   // stack = foo! foo!, thus return everything