从lua脚本调用c ++时如何获取多个返回值?

时间:2010-11-09 05:19:21

标签: c++ lua

//c++ funciton definition
int LS_SomeFucntion(LuaState* state)
{
LuaStack args(state);
//.. 
set<int>::iterator it = mySet.begin();
for(; it != mySet.end(); ++it)
{
    state.pushInteger(*it);
}
return mySet.size();

}

state->GetGlobals().Register("SomeFunction",LS_SomeFunction);

//lua scripts
??? = SomeFunction()

如何在lua脚本中获取SomeFunction()的返回值 何时调用函数时不知道大小?

1 个答案:

答案 0 :(得分:4)

您可以捕获表格中的所有返回值:

local rv = { SomeFunction() }

print('SomeFunction returned', #rv, 'values')
for i,val in ipairs(rv) do
    print(i,val)

或者使用变量参数列表处理它们:

function DoSomething(...)
   local nargs = select('#', ...)
   print('Received', nargs, 'arguments')
   for i=1,nargs do
      print(i,select(i,...))
end

DoSomething(SomeFunction())

当然,你的C函数应该只返回一个包含列表项的Lua表。我不熟悉LuaPlus,但从文档here来看,你需要这样的东西:

int LS_SomeFunction(LuaState* state)
{
   LuaObject table;
   table.AssignNewTable(state, mySet.size()); // presize the array portion

   int i = 1;
   for(set<int>::iterator it = mySet.begin(); it != mySet.end(); ++it)
       table.SetNumber(i++, *it);

   table.PushStack();
   return 1;
}

然后你就说:

local rv = SomeFunction()
print('SomeFunction returned', #rv, 'values')