lua_register在C++中存在问题。

我在使用lua_register函数将我的C/C++函数放入Lua时遇到了问题。以下是我项目的代码:

    LuaCore::LuaCore()
    {
         L = luaL_newstate();
         luaopen_io(L);
         luaopen_base(L);
         luaopen_table(L);
         luaopen_string(L);
         luaopen_math(L);
         luaL_openlibs(L);
     }

     LuaCore::~LuaCore()
     {
         if (L != NULL)
         {
             lua_close(L);
         }
     }

     void LuaCore::reportErrors(lua_State *l, int status)
     {
          if (status != 0)
          {
               agk::Message(lua_tostring(L, -1));
               lua_pop(L, 1);
          }
     }

     bool LuaCore::executeFile(const char* f)
     {
           int s = luaL_loadfile(L, f);
           if (s == 0)
           {
                s = lua_pcall(L, 0, LUA_MULTRET, 0);
           }
           reportErrors(L, s);
           return true;
      }

      void LuaCore::loadFunctions()
      {
            lua_register(L, "Print", Print);
      }

      void LuaCore::Print(lua_State *L)
      {
            int argc = lua_gettop(L);
            for (int n = 1; n <= argc; ++n)
            {
                 if (n > 2)
                 {
                     std::cout << lua_tostring(L,n);
                 }
           }
      }

以下是头文件:

    #pragma once

     extern "C"
     {
          #include "lua_lib\lua-5.3.1\src\lua.hpp"
     }

     #include <cstdlib>
     #include <cstring>
     #include <string>
     #include <iostream>
     using namespace std;

     class LuaCore
     {
      public:
          LuaCore();
          ~LuaCore();

          bool executeFile(const char* f);
          void reportErrors(lua_State *l, int status);
          void loadFunctions();

          void Print(lua_State *l);

          lua_State *L;

     };

同时这是错误:

    Error   1   error C2664: 'void lua_pushcclosure(lua_State
    *,lua_CFunction,int)' : cannot convert argument 2 from 'void (__thiscall
    LuaCore::* )(lua_State *)' to 'lua_CFunction'   C:\Program Files
    (x86)\The Game Creators\AGK2\Tier 2\apps\EasyCoreGamer_\LuaCore.cpp 46
    1   Template

并且还有intelliSense:

        2   IntelliSense: argument of type "void (LuaCore::*)(lua_State *L)"
        is incompatible with parameter of type "lua_CFunction"  c:\Program
        Files (x86)\The Game Creators\AGK2\Tier
        2\apps\EasyCoreGamer_\LuaCore.cpp   46  2   Template

我成功地使用了Lua运行C++的代码,并且能够在C++中调用Lua脚本。唯一的问题是尝试在lua脚本中调用C函数。我真的卡住了,谢谢您提前帮助!

点赞
用户536874
用户536874

你的打印函数类型错误。

你应该从下面的代码中获得相同的错误:

 lua_CFunction f{ Print };

在这里,f的类型是正确的。重写你的打印函数以适应该类型。

2017-05-23 16:47:09