Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to callback a lua function from a c function

Tags:

callback

lua

I have a C function (A) test_callback accepting a pointer to a function(B) as the parameter and A will "callback" B.

//typedef int(*data_callback_t)(int i);
int test_callback(data_callback_t f)
{
    f(3);   
}


int datacallback(int a )
{
    printf("called back %d\n",a);
    return 0;
}


//example 
test_callback(datacallback); // print : called back 3 

Now, I want to wrap test_callback so that they can be called from lua, suppose the name is lua_test_callback ;and also the input parameter to it would be a lua function. How should I achieve this goal?

function lua_datacallback (a )
    print "hey , this is callback in lua" ..a
end


lua_test_callback(lua_datacallback)  //expect to get "hey this is callback in lua 3 "

EDIT:

This link provide a way to store the callback function for later use .

//save function for later use 
callback_function = luaL_ref(L,LUA_REGISTRYINDEX);


//retrive function and call it 
lua_rawgeti(L,LUA_REGISTRYINDEX,callback_function);
//push the parameters and call it
lua_pushnumber(L, 5); // push first argument to the function
lua_pcall(L, 1, 0, 0); // call a function with one argument and no return values
like image 455
pierrotlefou Avatar asked Apr 22 '10 03:04

pierrotlefou


1 Answers

I'm not sure I understand your question, if you are asking what would lua_test_callback look in C, it should be something like this

int lua_test_callback(lua_State* lua)
{
    if (lua_gettop(lua) == 1 && // make sure exactly one argument is passed
       lua_isfunction(lua, -1)) // and that argument (which is on top of the stack) is a function
    {
        lua_pushnumber(lua, 3); // push first argument to the function
        lua_pcall(lua, 1, 0, 0); // call a function with one argument and no return values
    }
    return 0; // no values are returned from this function
}

You cannot just wrap test_callback, you need entirely different implementation to call Lua functions.

(edit: changed lua_call to lua_pcall as suggested by Nick. I still omitted any error handling for brevity)

like image 161
sbk Avatar answered Oct 23 '22 13:10

sbk