简体   繁体   中英

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; I am using tolua++ to export them to Lua

In 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++

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?

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. I guess tolua++ takes care of this for the classes/methods you exported.

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).

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. Not the cleanest way, IMHO, but could work.

I don't know tolua++, but both luabind and luabridge support what you need:
* option 1 is just to have the lua code do return whatever and you'll get the that in C++. This require that you'll have a template based version of run(), which returns a value.
* 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. There are several implementations of LuaEngine which support such a call:
LuaEngine * engine = new LuaEngine();
engine->run("function a(v) return v . 'a'; end ");
valua = engine->call("a", argument);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM