一個Lua函數我有一個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
現在,我想包裝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 "
編輯:
This link提供一種方式來存儲供以後使用的回調函數。
//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_pcall這將推動錯誤到堆棧,而不是僅僅崩潰。 – 2010-04-22 14:10:44
不錯的例子。但在實踐中,儘管一次又一次地寫入這樣的lua_test_callback()函數,但使用通用的,經過良好測試的接口會更好。 – 2010-04-22 18:12:48