创建一个调用其他Lua函数的C ++函数
问题描述:
我想知道是否有可能创建一个以Lua函数为参数来调用它的C ++函数.
I wonder if it's possible to create a C++ function that takes Lua function as argument to call it.
例如在Lua中,
function sub()
print('I am sub function')
end
function main()
callfunc(sub) //C++ function that takes a function variable to call
end
是否可以在C ++中创建callfunc()
函数?
Is it possible to create callfunc()
function in C++?
我正在使用SWIG.
答
You can create a callback by passing the Lua interpreter state down to the C++ function using the special lua_fnptr.i
header. The header file also contains further usage information.
%module callback
%include <lua_fnptr.i>
%{
void callfunc(SWIGLUA_FN fn) {
SWIGLUA_FN_GET(fn);
lua_call(fn.L,0,0);
}
%}
void callfunc(SWIGLUA_FN fn);
local cb = require("callback")
function hello()
print("Hello World!")
end
cb.callfunc(hello)
$ lua5.2 test.lua
Hello World!