LuaPlus:如何使函数返回表?

For*_*vin 6 c++ lua function lua-table luaplus

我想知道如何从C++端创建和注册一个函数,该函数在从Lua端调用时返回一个表.
我尝试过很多东西,但没有什么能真正起作用.:/

(对不起长代码)这个例子不起作用,因为Register()需要一个"luaCFunction"样式函数:

LuaPlus::LuaObject Test( LuaPlus::LuaState* state ) {
    int top = state->GetTop();
    std::string var( state->ToString(1) );

    LuaPlus::LuaObject tableObj(state);
    tableObj.AssignNewTable(state);

    if (var == "aaa")
        tableObj.SetString("x", "ABC");
    else if (var == "bbb")
        tableObj.SetString("x", "DEF");
    tableObj.SetString("y", "XYZ");
    return tableObj;
}
int main()
{
    LuaPlus::LuaState* L = LuaPlus::LuaState::Create(true);
     //without true I can't access the standard libraries like "math.","string."...
     //with true, GetLastError returns 2 though (ERROR_FILE_NOT_FOUND)
     //no side effects noticed though

    LuaPlus::LuaObject globals = L->GetGlobals();

    globals.Register("Test",Test);

    char pPath[MAX_PATH];
    GetCurrentDirectory(MAX_PATH,pPath);
    strcat_s(pPath,MAX_PATH,"\\test.lua");
    if(L->DoFile(pPath)) {
        if( L->GetTop() == 1 ) // An error occured
            std::cout << "An error occured: " << L->CheckString(1) << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试将其设置为luaCFunction-function时,它只会崩溃(0x3)并说:
断言失败:0,文件C:\ ......\luafunction.h,第41行

int Test( LuaPlus::LuaState* state ) {
    int top = state->GetTop();
    std::string var( state->ToString(1) );

    LuaPlus::LuaObject tableObj(state);
    tableObj.AssignNewTable(state);

    if (var == "aaa")
        tableObj.SetString("x", "ABC");
    else if (var == "bbb")
        tableObj.SetString("x", "DEF");
    tableObj.SetString("y", "XYZ");

    tableObj.Push();

    return state->GetTop() - top;
}
Run Code Online (Sandbox Code Playgroud)

澄清一下:从Lua方面我希望它可以像以下一样调用:

myVar = Test("aaa")
Print(myVar) -- output: ABC
Run Code Online (Sandbox Code Playgroud)

编辑:打印功能来自这里.而且基本上是导致这种情况无效的原因.打印只能打印字符串而不是表...如果你只返回1,上面的C++代码工作正常.

这是我的LuaPlus版本btw附带的文档:http://luaplus.funpic.de/

我真的希望你能帮助我..我已经开始认为这是不可能的.:'(

编辑: 我完全忘了说使用PushStack()导致错误,因为"该成员不存在"...

gre*_*olf 1

经过长评论讨论的一番艰苦探索后,我发布这个答案来帮助总结情况,并希望提供一些有用的建议。

OP 遇到的主要问题是printlua 测试脚本中调用了错误的函数。与原始代码相反,OP 正在测试的真实代码正在调用,Print(myVar)这是自定义提供的 lua_CFunction 而不是内置print函数。

不知何故,最终创建了一些实例化template <typename RT> class LuaFunction并调用了重载的operator()(). 通过检查luafunction.hluaPlus ,此调用中发生的任何 lua 错误都将被吞没,而不会进行任何类型的日志记录(对于 luaPlus 来说,这不是一个好的设计决策):

  if (lua_pcall(L, 0, 1, 0)) {
      const char* errorString = lua_tostring(L, -1);  (void)errorString;
      luaplus_assert(0);
  }
Run Code Online (Sandbox Code Playgroud)

为了帮助捕获类似的错误,我建议添加一个新的luaplus_assertlog宏。具体来说,该宏将包含errorString以便上下文不会完全丢失,并希望有助于调试。希望这一更改不会破坏luaplua_assertAPI 其他部分的现有使用。但从长远来看,最好进行修改,luaplus_assert使其实际上包含一些有意义的内容

无论如何,这是所做更改的差异:

LuaPlusInternal.h

@@ -81,5 +81,6 @@
 } // namespace LuaPlus

 #if !LUAPLUS_EXCEPTIONS
+#include <stdio.h>
 #include <assert.h>
 #define luaplus_assert(e) if (!(e)) assert(0)
@@ -84,5 +85,6 @@
 #include <assert.h>
 #define luaplus_assert(e) if (!(e)) assert(0)
+#define luaplus_assertlog(e, msg) if (!(e)) { fprintf(stderr, msg); assert(0); }
 //(void)0
 #define luaplus_throw(e) assert(0)
 //(void)0
Run Code Online (Sandbox Code Playgroud)

Lua函数.h

@@ -21,7 +21,7 @@
 class LuaFunction
 {
 public:
-   LuaFunction(LuaObject& _functionObj)
+   LuaFunction(const LuaObject& _functionObj)
    : functionObj(_functionObj) {
  }

@@ -36,7 +36,7 @@

    if (lua_pcall(L, 0, 1, 0)) {
      const char* errorString = lua_tostring(L, -1);  (void)errorString;
-           luaplus_assert(0);
+           luaplus_assertlog(0, errorString);
    }
    return LPCD::Type<RT>::Get(L, -1);
  }
Run Code Online (Sandbox Code Playgroud)

在上面的更改中,我选择不使用std::cerr只是因为 C++ 流往往比普通的旧 C 风格 io 函数更重。如果您使用 mingw 作为工具链,则尤其如此 -ld即使您的程序从不使用它,链接器也无法消除未使用的 C++ 流符号。

完成此操作后,下面是对 lua 函数进行不受保护的调用的示例,以便您可以errorString在崩溃之前看到打印输出:

// snip...
int main(int argc, const char *argv[])
{
    LuaStateAuto L ( LuaState::Create(true) );
    LuaObject globals = L->GetGlobals();
    globals.Register("Test", Test);
    globals.Register("Print", Print);
    if(argc > 1)
    {
      /*
      if (L->DoFile(argv[argc - 1]))
        std::cout << L->CheckString(1) << '\n';
      /*/
      L->LoadFile( argv[argc - 1] );
      LuaFunction<int> f ( LuaObject (L, -1) );
      f();
      //*/
    }
}
Run Code Online (Sandbox Code Playgroud)

运行上面的代码将触发崩溃,但会包含一条半有用的错误消息:

g++ -Wall -pedantic -O0 -g   -I ./Src -I ./Src/LuaPlus/lua51-luaplus/src plustest.cpp -o plustest.exe lua51-luaplus.dll

plustest.exe plustest.lua
plustest.lua:2: bad argument #1 to 'Print' (string expected, got table)Assertion failed!

Program: G:\OSS\luaplus51-all\plustest.exe
File: ./Src/LuaPlus/LuaFunction.h, Line 39

Expression: 0

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Run Code Online (Sandbox Code Playgroud)