c++ - 从字符串执行 Lua 函数

标签 c++ xml lua

我需要执行一个 lua 函数,它是 XML 文件的一部分。我将解析 XML 并将整个函数作为字符串加载。

当我尝试执行 lua_pcall 时,它让我attempt to call a nil value。 但是当我试图删除功能部分并单独使用内部逻辑时,它对我来说工作得很好。我需要了解我是否需要执行任何其他步骤才能作为函数执行。

初始化:

/* the Lua interpreter */
lua_State *luaState;
// initialize Lua 
luaState = luaL_newstate();
lua_register(luaState, "getValue", get_value);
lua_register(luaState, "setValue", set_value);
// load Lua base libraries 
luaL_openlibs(luaState);

工作: XML

-- lua script to be executed by this algorithm
-- use following API calls to get and set function block data
-- local IN1 = getValue("IN1")
-- setValue("OUT1", value)
 setValue("RequestAccepted", "true");

-- lua script

C++代码:

TAlgoTable::iterator iter = algoTable.find("RequestAccepted");
if (luaL_dostring(luaState, iter->second.c_str()))
{
    printf("Failure at Algorithm : 'RequestAccepted' Reason : %s", lua_tostring(luaState, -1));
}

不工作:

 -- lua script to be executed by this algorithm
function RequestAccepted()
 -- use following API calls to get and set function block data
 -- local IN1 = getValue("IN1")
 -- setValue("OUT1", value)
 setValue("RequestAccepted", "true");

end -- lua script

C++代码:

lua_getglobal(luaState, "RequestAccepted"); // function to be called 
if (lua_pcall(luaState, 0, 0, 0)) {
    printf("Failure at Algorithm : 'RequestAccepted' Reason : %s", lua_tostring(luaState, -1));
}

最佳答案

我发现并理解我需要将函数加载到缓冲区中。 以下链接帮助我解决了 http://gouthamanbalaraman.com/blog/minimal-example-lua-function-cpp.html

关于c++ - 从字符串执行 Lua 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176098/

相关文章:

c++ - lua/C++ 对象与静态成员的绑定(bind)

c++ - 我可以重用无效的迭代器吗?

java - 在 Java 中,对于 XML 编码/解码,我们应该使用 JAXB、JIBX、CASTOR、ADB etx 中的哪个实用程序?

xml - 从 XML 到 Excel 的舍入数字

表中的 Lua 拉丁字符

c - 从 Lua 调用的推送表的 C 函数应该返回什么?

c++ - 在 C 中导航数组(性能)?

c++ - CUBLAS 矩阵乘法与行主数据无转置

c++ - 构建自定义编译库的更好方法

xml - 棘手的 xpath 查询