【问题标题】:LuaPlus: How to make a function return a table?LuaPlus:如何让函数返回一个表?
【发布时间】:2013-11-18 13:22:20
【问题描述】:

我想知道如何从 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;
    }
}

当我尝试将其设置为 luaCFunction 函数时,它只会崩溃 (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;
}

为了澄清:从 Lua 方面我希望它可以像这样调用:

myVar = Test("aaa")
Print(myVar) -- output: ABC

编辑:打印功能来自here。基本上是这个不起作用的原因。 Print 只能打印字符串而不是表格...如果您只返回 1,上面的 C++ 代码就可以正常工作。

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

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

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

【问题讨论】:

  • 如果将return state-&gt;GetTop() - top; 替换为return 1; 会发生什么? (在Test函数的最后一行)errorString包含什么?
  • 是的,我得到了同样的错误。
  • 你是如何从 C++ 调用测试脚本的?
  • LuaPlus 从 lua_pcall 得到错误,然后完全没有做任何事情。然后它失败了一个不提供额外信息的断言。该 errorString 变量(除非它被神奇地用于我没有看到的某个地方)很可能包含有用的信息。
  • 不幸的是,所有这些混乱的最终结果是,我认为所写和问的问题完全不正确,最终对其他人没有帮助。我不知道 SO 指导方针是什么,但我可能会建议撤回这个问题,或者至少编辑它以包含正在运行的实际 lua 脚本和所涉及的打印功能。

标签: c++ function lua lua-table luaplus


【解决方案1】:

经过长时间的评论讨论后,我发布此答案以帮助总结情况,并希望提供一些有用的建议。

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

不知何故,这最终创建了template &lt;typename RT&gt; class LuaFunction 的一些实例化并调用了重载的operator()()。通过检查 luaPlus 中的luafunction.h,在此调用中发生的任何 lua 错误都将在没有任何日志记录的情况下被吞没(对 luaPlus 而言,这不是一个好的设计决策):

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

为了帮助捕获未来的此类错误,我建议添加一个新的 luaplus_assertlog 宏。具体来说,这个宏将包含 errorString,这样上下文就不会完全丢失,并希望有助于调试。此更改希望不会破坏 API 其他部分对 luaplua_assert 的现有使用。但从长远来看,修改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

LuaFunction.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);
  }

在上面的更改中,我选择不使用 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();
      //*/
    }
}

运行上述将触发崩溃,但会包含一个半有用的错误消息:

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.

【讨论】:

    【解决方案2】:

    首先你可以尝试使用RegisterDirect()注册函数,这样可以避免lua_CFunction的问题,查看luaplus手册。像这样

    LuaPlus::LuaObject globals = L->GetGlobals();
    
    globals.RegisterDirect("Test",Test);
    

    第二个如果我记得创建一个表有两个解决方案,像这样

    //first
    LuaObject globalsObj = state->GetGlobals();  
    LuaObject myArrayOfStuffTableObj = globalsObj.CreateTable("MyArrayOfStuff"); 
    
    //second
    LuaObject aStandaloneTableObj;  
    aStandaloneTableObj.AssignNewTable(state);  
    

    检查你是否使用了正确的功能。

    第三个我记得lua栈对象不是luaobject,他们有一个转换,可能你可以试试这个

    LuaStackObject stack1Obj(state, 1);
    LuaObject nonStack1Obj = stack1Obj;
    

    第四,就像你上面给出的函数Test(),你已经压入lua堆栈的表tableObj,你必须记住清除对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      相关资源
      最近更新 更多