lua-users home
lua-l archive

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




LUA Newbie question:


How do call a Lua function from C or C++, passing parms, and obtain the return value (or values)?

The documentation contains no COMPLETE examples of this, as far as I can tell.

I've found examples, none of which work.



Can one simply load a function (causing it to be pushed onto the stack), then push any parms, and invoke lua_call()?


Please consider the following code:

--------------------------------------------------
static const char cAdd[] =
"function add ( x, y )\r\n"
"    return x + y\r\n"
"end\r\n"
;
enum LOADSTATUS { NEVER_ATTEMPTED, LOADED, LOAD_FAILED };

static LOADSTATUS eLoadStatus = NEVER_ATTEMPTED;

static void vTestAdd3()
{
    lua_State* L = lua_open();
    luaL_openlibs( L );

    int iStatus = 0;
    int iSum = 0;

    if ( NEVER_ATTEMPTED == eLoadStatus )                // STATEMENT C
    {
        iStatus = luaL_loadstring(L, cAdd);
        if ( 0 == iStatus )
        {
            lua_setfield(L, LUA_GLOBALSINDEX, "my_add");    // STATEMENT A
            eLoadStatus = LOADED;
        }
        else
            eLoadStatus = LOAD_FAILED;
    }

    if ( LOADED == eLoadStatus )
    {
        lua_getfield(L, LUA_GLOBALSINDEX, "my_add");        // STATEMENT B
        lua_pushinteger(L, 77 );
        lua_pushinteger(L, 22 );
        int iNumElementsPreCall = lua_gettop(L);
        iStatus = lua_pcall(L, 2, 1, 0);
        if ( 0 == iStatus )
        {
            int iNumElementsPostCall = lua_gettop(L);
            iSum = lua_tointeger(L, -1);            // STATEMENT D
        }
    }

    vReport_errors(L, iStatus);
    lua_close(L);
}
-----------------------------------------------------------------------------

[The above code differs a little from what I'd write for actual use. It is for illustration.]


Following statement D, iSum IS ALWAYS ZERO (0).

If I omit statements A and B iSum is still zero.


iNumElementsPreCall is 3, as expected, and iNumElementsPostCall is 1, as expected.

 
Does the above code reflect a correct understanding of Lua? What am I doing wrong?

Say, could my math be off? Is 77+22 = 0? I tried checking, but ran out of fingers.

Or does Lua always perform modulo 99 arithmetic?

Any help appreciated.