从C++调用Lua函数与定义了2个函数不起作用。

我有一个 Lua 脚本,里面有两个函数:

function CallbackServerStatus ()
    print("Status exec")
end

function CallbackServerInit ()
    print("Server initialized\n")
end

这是我在 C++ 中尝试调用我的 Lua 函数的方式:

printf("LUA | Exec LUA: CallbackServerInit()\n");
luaL_dofile(LuaEngine::state, "loaders/test.lua");
lua_getglobal(LuaEngine::state, "CallbackServerInit");
lua_pcall(LuaEngine::state, 0, 0, 0);

但是在控制台上,“Server initialized\n”似乎并没有显示出来。我在这里做错了什么吗??甚至没有错误出现,只有在我删除CallbackServerStatus()函数后才能看到“Server initialized\n”字符串。

点赞
用户520499
用户520499

我认为你可能需要重构你的代码。

void execute(std::string szScript)
{
  int nStatus = 0;

  nStatus = luaL_loadfile(L, szScript.c_str());
  if(nStatus == 0){ nStatus = lua_pcall(L, 0, LUA_MULTRET, 0); }

  error(nStatus);
}

void callFunction(std::string szName)
{
    int nStatus = 0;

    lua_getglobal(L, szName.c_str());
    nStatus = lua_pcall(L, 0, LUA_MULTRET, 0);

    error(nStatus);
}

void error(int nStatus)
{
    if(nStatus != 0)
    {
      std::string szError = lua_tostring(L, -1);
      szError = "LUA:\n" + szError;
      MessageBox(NULL, szError.c_str(), "Error", MB_OK | MB_ICONERROR);
      lua_pop(L, 1);
    }
}

我已经为我的应用程序写了这个。您也可以使用它。这样,您可以观察在编译脚本或调用函数时出现的任何类型的错误。

execute("C:\test.lua");
callFunction("MyFunc");
2013-10-20 17:02:35
用户2077052
用户2077052

哦,我发现我的脚本中有一个不可打印字符导致脚本失败。

感谢回答!

2013-10-20 21:08:53