在我的C ++应用程序中,我有一个包含XML数据的字符串。假设我有一个属性Number1和一个属性Number2。
我想将该字符串发送到Lua脚本并让它返回修改后的XML字符串。假设它添加了一个新的属性Product,其值为Number1和Number2。
是否可以使用C ++ / Lua轻松完成,如果是这样的话?
答案 0 :(得分:1)
有几种方法可以处理the Lua Users Wiki中列出的XML数据。更好的选择涉及回调C(例如LuaXML和LuaExpat),所以只有在有其他理由使用Lua而不仅仅是解析XML时才有意义。
答案 1 :(得分:0)
我自己不是Lua用户......但只是浏览文档,似乎可以使用lua_pushstring()
将一个以null结尾的C字符串的副本放入Lua堆栈中:
http://pgl.yoyo.org/luai/i/lua_pushstring
虽然lua_popstring()
之类的内容没有具体的定义,但您可以自己定义类似的内容:
std::string lua_popstring(lua_State *L)
{
std::string tmp = lua_tostring(L, lua_gettop(L));
lua_pop(L, 1);
return tmp;
}
有了这个,您应该能够修改标准示例,以便将数据传递到Lua并为您的目的返回结果:
答案 2 :(得分:0)
你可以这样做(不是这可能不是100%正确,因为我不在乎它不包括错误处理):
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
调用的lua函数可能如下所示:
function modifyXml(xml)
-- do something with xml here
return xml
end
答案 3 :(得分:0)
如果您使用Luabind,它在C ++中可能看起来像这样:
std::string result = luabind::call_function<std::string>(
"yourLuaFunction", inputXmlString);
你当然会在Lua中实现yourLuaFunction
,在你的C ++程序中实现require
Lua模块。