问题
I wonder if it's possible to create a C++ function that takes Lua function as argument to call it.
For example in Lua,
function sub()
print('I am sub function')
end
function main()
callfunc(sub) //C++ function that takes a function variable to call
end
Is it possible to create callfunc()
function in C++?
I'm using SWIG by the way.
回答1:
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!
来源:https://stackoverflow.com/questions/51145432/creating-a-c-function-that-calls-other-lua-function