how to callback a lua function from a c function

后端 未结 2 824
孤街浪徒
孤街浪徒 2021-02-14 01:52

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         


        
2条回答
  •  执念已碎
    2021-02-14 02:40

    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)

提交回复
热议问题