lua-users home
lua-l archive

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


Hello, (first post, sorry if I miss some list etiquette details)

I have made a replacement print function in C++ to put what the user prints onto the stack so I can pull it off and send it out to the user on a socket.

This is my print function:

static int return_print (lua_State* L)
{
    int nargs   = lua_gettop (L);
    int returns = 0;
    
    lua_getglobal (L, "tostring");

    for (int i = 1; i <= nargs; i++)
    {
        const char *s;
        lua_pushvalue (L, nargs + 1);  /* function to be called */
        lua_pushvalue (L, i);   /* value to print */
        lua_call (L, 1, 1);
       
        ++returns;

        // don't pop - we're leaving them on the stack
    }
    return returns;
}

It gets called and works fine - leave the stack with the original stack, plus a function and my new results, and returns the number of results. It works with 1 or more results.

Then I call some user code with:

int err = luaL_loadstring (luaVM, inCmd.toUTF8()) || lua_pcall (luaVM, 0, LUA_MULTRET, 0); // 0 args, any results
         
        if (err)
        {
            String problem	= String::fromUTF8 (lua_tostring (luaVM, -1));
            lua_pop (luaVM, 1);  // pop error message from the stack 
            response = "MeshScript error: " + problem;
        }
        else
        {
            int nargs = lua_gettop (luaVM);
	    etc.

nargs is always blank. 

If I use the system print, it prints to the console, and my version gets called - that seems ok.

The problem seems to occur after running my function. Part way through the post C function call my stack gets wiped.

Am I missing something?

Bruce