Question

I want to setup a couple of functions in Lua for scripters but when those functions are invoked, I'd like them to actually invoke a single function with a parameter that I define. This might look like:

Lua:

    foo1()
    foo2()

C++:

int myFunction( lua_State * context )
{
    int numArgs = lua_gettop( context );
    int topOfStack = -3;
    bool lightUserDataFlag = lua_islightuserdata( context, topOfStack );

    if( lightUserDataFlag )
    {
    }
}

}

So I am a little confused on the setup. I am trying to register the callback with a param. This is what I have so far and there is something that is not saving the param with the function registration; it seems to only save the last param I add.

void setupCallback()
{
    lua_register( context, "foo1", Callback);
    lua_pushlightuserdata( context, &value[0] );
    lua_register( context, "foo2", Callback);
    lua_pushlightuserdata( context, &value[1] );
}

When lua invokes my callback, I always see the value[1], never the value[0]. I played with the notion of registering the callback and then adding a table, but I'm not sure that this will get me any further.

As to the why: I am trying to abstract function names to make writing code for our lua programmers easier, but those simply need to translate into the same parameterized function. Think of it add changing settings by passing a single param, but naming that differently.

Thoughts?

Was it helpful?

Solution

You likely want to attach those context values as upvalues of your function. Take a look at lua_pushcclosure().

Incorporating Mickey Kawick's comment:

int Callback (lua_State *context)
{
    int val= lua_tointeger( context, lua_upvalueindex(1) );
    cout << val << endl;
    ...
} 

void setup()
{
    lua_pushnumber( context, 3 );
    lua_pushcclosure( context, Callback, 1 );
    lua_setglobal( context, "foo1" );

    lua_pushnumber( context, 42 );
    lua_pushcclosure( context, Callback, 1 );
    lua_setglobal( context, "foo2" );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top