创建一个调用其他Lua函数的C ++函数 [英] Creating a C++ function that calls other Lua function

查看:80
本文介绍了创建一个调用其他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!

这篇关于创建一个调用其他Lua函数的C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆