我有一个C函数(A)test_callback接受一个函数(B)的指针作为参数,A将"回调"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
Run Code Online (Sandbox Code Playgroud)
现在,我想换行test_callback以便可以从lua调用它们,假设名称是lua_test_callback;并且它的输入参数也是lua函数.我该如何实现这一目标?
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 "
Run Code Online (Sandbox Code Playgroud)
编辑:
此链接提供了一种存储回调函数以供以后使用的方法.
//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
Run Code Online (Sandbox Code Playgroud)
我不确定我理解你的问题,如果你问的是lua_test_callbackC中的内容,它应该是这样的
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
}
Run Code Online (Sandbox Code Playgroud)
你不能只是换行test_callback,你需要完全不同的实现来调用Lua函数.
(编辑:改lua_call到lua_pcall.由尼克的建议我还是省略任何错误处理的简洁)