如何从c函数回调lua函数 [英] how to callback a lua function from a c function
问题描述
我有一个C函数(A) test_callback
接受指向函数(B)的指针作为参数,A将回调B.
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
现在,我想换 test_callback
,以便它们可以从lua调用,假设名称为 lua_test_callback
;并且它的输入参数将是lua函数。我应该如何实现这个目标?
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 "
编辑:
此链接提供了一种存储回调函数供以后使用的方法。
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
推荐答案
我不知道我理解你的问题,如果你问什么 lua_test_callback
看看C,它应该是这样
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
}
$ c> test_callback ,您需要完全不同的实现来调用Lua函数。
You cannot just wrap test_callback
, you need entirely different implementation to call Lua functions.
(edit:changed lua_call
到
lua_pcall
,我仍然省略任何错误处理为简洁)
(edit: changed lua_call
to lua_pcall
as suggested by Nick. I still omitted any error handling for brevity)
这篇关于如何从c函数回调lua函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!