【发布时间】:2016-09-07 15:35:08
【问题描述】:
我需要执行一个 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));
}
【问题讨论】:
-
在第一个示例中,您调用
lua_dostring()来解析和执行Lua 代码。在第二个例子中,你不是,除非你忽略了那一点。