我需要执行一个 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/