In my C++ app, I have a string which contains XML data. Let's say I have an attribute Number1 and an attribute Number2.
I want to send that string to a Lua script and have it return a mo开发者_开发知识库dified XML string. Let's say it adds a new attribute Product with the value of Number1 and Number2.
Is that easily done using C++/Lua, and if so how?
There are several methods to work with XML data listed at the Lua Users Wiki. The better options involve calls back to C (e.g. LuaXML and LuaExpat) so this only makes sense to do if there are other reasons to use Lua beyond just parsing XML.
Not a Lua user myself...but just browsing the documentation, it seems that you can use lua_pushstring()
to put a copy of a null-terminated C string into the Lua stack:
http://pgl.yoyo.org/luai/i/lua_pushstring
Although there is no specific definition for things like lua_popstring()
you can define something like that yourself:
std::string lua_popstring(lua_State *L)
{
std::string tmp = lua_tostring(L, lua_gettop(L));
lua_pop(L, 1);
return tmp;
}
With that in hand you should be able to modify the standard example for passing data into Lua and getting a result back for your purpose:
http://lua-users.org/wiki/SimpleLuaApiExample
You could do it similar to this (not this might not be 100 % correct due to being out of my mind and it doesn't include error handling):
lua_getglobal(L, "modifyXml"); // push function on stack by name
lua_pushstring(L, xml); // push the xml string as parameter
lua_pcall(L, 1, 1, 0); // call the function with 1 parameter, 1 return value and no error handler
strcpy(xml, lua_tostring(L, -1)); // get the top of the stack as a string and copy it to xml
lua_pop(xml, 1); // remove the string from the stack
The lua function called could look like this:
function modifyXml(xml)
-- do something with xml here
return xml
end
If you use Luabind it could look something like this in C++:
std::string result = luabind::call_function<std::string>(
"yourLuaFunction", inputXmlString);
You would implement yourLuaFunction
in Lua of course, and require
that Lua module from within your C++ program.
精彩评论