[英]Embedding Lua in C++: Accessing C++ created through Lua, back in C++ (or returning results back from Lua to C++)
The title probably sounds a bit recursive - but this is what I am trying to do: 标题听起来似乎有些递归-但这就是我想要做的:
I have C++ classes Foo and Foobar; 我有C ++类Foo和Foobar; I am using tolua++ to export them to Lua
我正在使用tolua ++将它们导出到Lua
In Lua: 在Lua:
function wanna_be_starting_something()
foo = Foo:new()
fb = Foobar:new()
-- do something
foo.setResult(42) -- <- I want to store something back at the C++ end
end
In C++ 在C ++中
int main(int argc, char argv[])
{
MyResult res;
LuaEngine * engine = new LuaEngine();
engine->run('wbs-something.lua');
// I now want to be able to access the stored result, in variable res
};
So my question is this: how do I pass data from a C++ object that is being manipulated by Lua, back into a C++ program? 所以我的问题是这样的:如何将Lua操纵的C ++对象中的数据传递回C ++程序中?
To understand how to exchange data back and forth, you should learn about the Lua stack that is the structure Lua uses to communicate with the host program. 要了解如何来回交换数据,您应该了解Lua堆栈,它是Lua与主机程序进行通信所使用的结构。 I guess tolua++ takes care of this for the classes/methods you exported.
我想tolua ++会处理您导出的类/方法。
Here there is a good start: http://www.lua.org/pil/24.html is for Lua 5.0 but there are indications on how to make it work with 5.1 (which I assume is the Lua version you're using). 这是一个很好的开始: http : //www.lua.org/pil/24.html适用于Lua 5.0,但是有迹象表明如何使其与5.1一起使用(我假设这是您使用的Lua版本) )。
If you don't want to dig into all the details, you can always resort to create an ad-hoc C++ method that sets values into a global object. 如果您不想深入研究所有细节,则始终可以使用创建将值设置为全局对象的临时C ++方法。 Not the cleanest way, IMHO, but could work.
恕我直言,这不是最干净的方法,但是可以工作。
I don't know tolua++, but both luabind and luabridge support what you need: 我不知道tolua ++,但是luabind和luabridge都支持您所需要的:
* option 1 is just to have the lua code do return whatever
and you'll get the that in C++. *选项1只是让lua代码
return whatever
,您将在C ++中得到它。 This require that you'll have a template based version of run(), which returns a value. 这要求您具有run()的基于模板的版本,该版本返回一个值。
* option 2 is to use the lua engine to define a function and then use the engine's call method with the function name and parameters. *选项2是使用lua引擎定义函数,然后将引擎的call方法与函数名称和参数一起使用。 There are several implementations of LuaEngine which support such a call:
LuaEngine有几种支持这种调用的实现:
LuaEngine * engine = new LuaEngine();
engine->run("function a(v) return v . 'a'; end ");
valua = engine->call("a", argument);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.