Creating a C++ function that calls other Lua function

拥有回忆 提交于 2019-12-23 23:28:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!